addEventListener/attachEvent & Function References
patrick — Wed, 2006-09-13 16:42
Craig Fowler stumped me today until he provided a further sampling of his code. Shortly thereafter I realized what the issue was as I've run into the same issue in the past (& hopefully this page will prevent me being stumped in the future).
The code he initially presented me with was
<a onclick="obj1.doSomething();"> ...
and he stated he was having issues with using this.someMethod();
inside of obj1
... i.e.
var obj1 = new function() {
this.name = 'Object 1';
this.doSomething = function() {
this.someMethod(
'Hello, my name is ' + this.name
);
};
this.someMethod = function( text ) {
alert( text );
}
};
Granted, you really wouldn't write code this bad, but we're just whipping up a quick example to test the problem.
well, putting <a href="#" onclick="obj1.doSomething();">
works just fine... At which point Craig mentioned that that was the end result he was wanting... what he was using to attach it was this snippet from a function -
if(eventElement.addEventListener) { eventElement.addEventListener("click", subscribers[currentSubscription].shout, false) } else if(eventElement.attachEvent) { eventElement.attachEvent("onclick", subscribers[currentSubscription].shout) }
I had to laugh as soon as I saw it because I remembered doing the same thing. Javascript variables are not really variables... what you create with var a = 1 + 1;
is a reference to a protected variable inside the Javascript engine. There are alot of detailed discussions about this elsewhere so I won't go that route.
Initially looking at the code you may think that the function you're giving to addEventListener
/attachEvent
is going to be the code that goes inside the onclick
event... i.e.
element.onclick = function() { passedFunction(); }
But in reality what is happening is this -
element.onclick = passedFunction;
I don't know of any good solutions. The solution I had come up with before was to write a proxy function. Craig did the same thing in writing a proxy method into the parent class. A proxy function would be something like the following -
function proxyFunction( evt ) { evt = evt || window.event; ...code to determine what function *really* needs to be called... if ( realFunction ) { realFunction(); } }