Hi,
On Jan 8, 2009, at 08:40 , Matteo wrote:
> I noticed that in some examples at developers.apple.com Apple is
> adding event listeners on the fly and removing them as soon as they
> are not required. In the drag-n-drop example they add the touchmove
> and touchend events at the end of the touchstart:
>
> this.element.addEventListener('touchmove', function(e) { return
> self.onTouchMove(e) }, false);
> this.element.addEventListener('touchend', function(e) { return
> self.onTouchEnd(e) }, false);
>
> and they try to remove them on touchend:
>
> this.element.removeEventListener('touchmove',function(e){return
> self.onTouchMove(e)},false);
> this.element.removeEventListener('touchend',function(e){return
> self.onTouchEnd(e)},false);
>
> As far as I can tell there's no way to remove an anonymous function
> with removeEventListener. Initially I thought it was a webkit feature
> but it turned out that the events are indeed never removed, so at
> every touchstart two new events are appended (a big memory problem).
Indeed, this is a poor way (an no-op) way to deal with event handlers
scoped to a particular object. The most convenient way I know to do
this is to have your JS object implement the DOM EventListener
interface:
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
For instance:
function MyClass () {
// say we have a this.element here
this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false);
// you can then remove event listeners with
// this.element.removeEventListener('touchmove', this, false);
}
// this is the sole method from EventListener to implement,
// and this is where events will be routed when "this" is used
// as the "listener" parameter of .addEventListener()
MyClass.prototype.handleEvent = function (event) {
switch (event.type) {
case 'touchmove' :
this.onTouchMove(event);
break;
case 'touchend' :
this.onTouchEnd(event);
break;
};
MyClass.prototype.onTouchMove = function (event) {
// do something here
};
MyClass.prototype.onTouchEnd = function (event) {
// do something here
};
This is a relatively lesser known way to deal with events within
scoped to a JS instance object, but it works great.
Antoine
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"iPhoneWebDev" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/iphonewebdev?hl=en
-~----------~----~----~----~------~----~------~--~---