Saturday, December 09, 2006

Contextually dispatching events

I just realized that I could implement EventDispatcher.prototype.dispatchEvent as (difference emphasized):

dispatchEvent : function(type, event) {
 if (this.events[type]) {
  for (var i in this.events[type]) {
   if (typeof this.events[type][i] == 'function') {
    this.events[type][i](event);
   // Accepts an array of the contextual object and the function to call
   } else if (typeof this.events[type][i] == 'object') {
    this.events[type][i][1].call(this.events[type][i][1], event);
   }
  }
 }
}

This makes it much easier to keep this references happy and I can't believe I didn't think of that until just now, since I used almost the same code to call parent object methods from a child that had overridden the method. So now you can create listeners from within object methods like this:

myeventdispatcher.addEventListener('load', new Array(this, this.myLoadEventListener));

or this:

myeventdispatcher.addEventListener('load', new Array(this, MyObject.prototype.myLoadEventListener));

Side note: I also realize I need to find a way of posted syntax-highlighted code consistently and easily. The code I had posted on Simple Event Generation came from copying the source into Kate, exporting the highlighted code as HTML, and pasting the mass of spans into Blogger.

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home