- From: David Flanagan <david@oreilly.com>
- Date: Fri, 15 Jun 2001 09:14:35 -0700
- To: PBWiz@mail.pbwizard.com
- CC: jst@netscape.com, www-dom@w3.org, jim@jibbering.com
Everyone, Since I started this thread, let me summarize some of the responses. I had proposed the following: element.addEventListener("click", { message: "Hello world", handleEvent: function(e) { alert(this.message); } }, false); Johnny Stenback wrote to say that recent (0.9.1?) Mozilla versions and Netscape 6.1 beta already support this usage. I'd be interested to know whether the rationale for implementing this was the same as the one I gave, and I wonder whether the fact that it is implemented will lend any weight to the idea of formalizing it in for the Level 3 Events spec... Jeff Yates also responded with the following brilliant piece of code: function objectEventHandler( object, methodName, element){ element.addEventListener( "click", function(evt){ object[methodName](evt); }, false ); } This code relies on a nested function literal (and the closure that goes along with it to save its scope) to hold on to the reference to the object on which the method is to be called. Very cool. If it were me, I'd rewrite it like this, to change the outer method name, to use a funciton reference instead of a method name, and to use Function.call (part of JavaScript 1.5, and ECMAScript v3): function registerEventListener(element, eventtype, object, func, captures) { element.addEventListener(eventtype, function(e) { func.call(object, e); } } captures); I haven't tested this, but you should at least get the idea. Thanks Jeff! Jim Ley wrote that my proposal is unnecessary because it could just be replaced with: element.addEventListener("click", ({ message: "Hello world", handleEvent: function(e) { alert(this.message); } }).handleEvent, false); Unfortunately, this misses the point. I believe that this syntax still just registers a function, and that function will be invoked in such a way that the this keyword refers to the event target, or (depending on implementation) to the global object, or is undefined. When the function is called, "this.message" will not resolve the way we want it to. David Flanagan
Received on Friday, 15 June 2001 13:11:14 UTC