Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – Working around by storing reference to functions


You can work around this problem by storing references to functions:

import js.Lib;
import js.Dom;

class Main
{
   static var but1:js.Button;
   static var but2:js.Button;
   static var myHandler:js.Event->Void;
   
   public static function main(): Void
   {
      but1 = cast Lib.document.getElementById("button1");
      but2 = cast Lib.document.getElementById("button2");
      
      myHandler = clickHandler;
      
      untyped but1.addEventListener("click", myHandler);
      but2.onclick = removeHandler;
   }
   
   public static function clickHandler(ev : js.Event)
   {
      js.Lib.alert("You've clcked.");
   }
   
   public static function removeHandler(ev:js.Event)
   {
      untyped but1.removeEventListener("click", myHandler);
   }
}

What just happened?

Note the use of the myHandler variable—now, instead of creating a new closure every time, we store one into myHandler. This way, it is possible to remove our...