Javascript Class Event Handlers
For a while now I've been trying to make my javascript code more object oriented by using javascript "classes". Now classes in javascript are a little odd: there's no class keyword. Methods are just functions inside a "class" function. Events have a few quirks too and I was having trouble getting events to play well with classes.
Here's an example class:
-
function ExampleClass() {
-
// methods
-
this.exampleFunction = function() {
-
alert('HI!');
-
}
-
this.eventHandler = function() {
-
this.exampleFunction();
-
}
-
// constructor
-
setTimeout(function() { this.eventHandler(); }, 10000); // run eventHandler in 10 seconds
-
}
The problem I was having was that when the timeout called eventHandler it didn't have a reference to this anymore! There is a neat trick to get around this though:
-
var me = this;
-
setTimeout(function() { me.eventHandler(); }, 10000);
By setting a variable (me) equal to this and using that I can keep a reference to the class when the event fires. I saw this trick once or twice in actionscript, but never thought to apply it to javascript.
There is a neat article about this I found. Sjoerd Visscher's weblog has a whole bunch of good stuff about really advanced javascript.
I found a recent post where it looks like someone else was running into the same problem and the commenters suggested the same solution.
I have been fighting this for a couple of days. I didn’t want to have to use the class instance in the callbacks that would just be dumb. I know I had to use a closure but was having trouble getting it to work. Thanks
Hi. I apologize for my last message. The thing is that your explanation wasn’t very clear about WHERE to declare the reference. It actually works when declaring it inside the constructor (which is a wierd way to handle scope), but a great solution for such purose. I’ve seen a lot of dirty workarrounds to handle multiple ajax requests and this is the first I see that can mantain a real unique instance in a class. Thank you very much for sharing this.