Event Handlers and Callback Functions in JavaScript
By Sjoerd Visscher
2006-08-19
The Trick
The problem is as follows: Methods use this to refer to the object it is a method of. But, when using a method as event handler or callback function, this does no longer point to that object. The trick is to use the closure like behaviour of functions, so that the method will always have access to it's object. Let's look at an example: We want to use a method of an Alerter class as an event handler. function Alerter(text) {
this.text=text;
var me=this;
this.invoke=function () {
alert(me.text);
}
}
var sayHi=new Alerter('Hello, world!');
div.attachEvent('onclick', sayHi.invoke);So, instead of using this, we use a variable me, that equals this when the invoke method is created. And, in contrast to this, me will keep refering to the correct Alerter object, even when it's passed as a function to the attachEvent method of an HTML element.
Tutorial Pages:
»
Introduction
» The Trick
»
Higher Order Programming again
»
Conclusion
This article is licensed under the Creative Commons
|

|