blog.vorpal.cc

Hi! My name is David Hogue. I write code in Bend, Oregon.

March 29, 2006

Javascript Class Event Handlers

Filed under: — David @ 11:52 pm

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:

JAVASCRIPT:
  1. function ExampleClass() {
  2.      // methods
  3.     this.exampleFunction = function() {
  4.         alert('HI!');
  5.     }
  6.     this.eventHandler = function() {
  7.         this.exampleFunction();
  8.     }
  9.     // constructor
  10.     setTimeout(function() { this.eventHandler(); }, 10000);    // run eventHandler in 10 seconds
  11. }

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:

JAVASCRIPT:
  1. var me = this;
  2. 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.

2 Responses to “Javascript Class Event Handlers”

  1. 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

  2. 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.

Leave a Reply