Prev | Current Page 739 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"

A better
way to implement events is to use the addEventListener() DOM method. This method is not
supported on every modern browser (see Internet Explorer before version 7), so it must be wrapped in a
compatibility layer. One possible solution is the following code snippet:
import js.Dom;
class DomListener
{
public static function add(el : Dynamic, t : String, f : Event - > Void)
{
if(Reflect.hasField(js.Lib.window, ???addEventListener???))
(continued)
398
Part II: Server Side, JavaScript, and Flash: Oh My!
{
add = function(el, t, f)
{
el.addEventListener(t, f, false);
};
} else {
add = function(el, t, f)
{
el.attachEvent(???on??™ + t, f);
};
}
add(el, t, f);
}
public static function remove(el : Dynamic, t : String, f : Event - > Void)
{
if(Reflect.hasField(js.Lib.window, ???removeEventListener???))
{
remove = function(el, t, f)
{
el.removeEventListener(t, f, false);
};
} else {
remove = function(el, t, f)
{
el.detachEvent(???on??™ + t, f);
};
}
remove(el, t, f);
}
}
The add() method simply adds a new listener to the element passed as the first argument; the argument
is the Dynamic type because not only objects of type HtmlDom support events, but the Window object
supports them, too.


Pages:
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751