micolous.id.au

The result of a blogging accident

Passing parameters in .addEventListener in JS

[element.addEventListener][ael] in Javascript allows you to pass an Object as the second parameter that has a `handleEvent` method exposed. This allows you to object orientate everything, however you can’t normally pass additional parameters (for example, if you’re trying to use the same event handler for many sub-objects) doesn’t work. For example, you’re stuck with just:

function MyClass() {
  for (x = 0; x < 10; x++) {
    someElement.childNodes[x].addEventListener("click", this, false);
  }
  this.handleEvent = function (e) {
    if (e.type == "click") {
      // .. do something here
    }
  };
}

You can’t use `eval()` here with an anonymous function, as `this` will not have the right value. However, you can trick the system into letting you pass additional parameters by implementing another class in the middle like so:

function MyClass() {
  for (x = 0; x < 10; x++) {
    someElement.childNodes[x].addEventListener("click", new MyClassDoSomethingClickHandler(this, x), false);
  }
  this.doSomething = function(x) {
    // do something here...
  }
}

function MyClassDoSomethingClickHandler(obj, x)
  this.obj = obj;
  this.x = x;
  this.handleEvent = function (e) {
    if (e.type == 'click') {
      this.obj.doSomething(this.x);
    }
  };
}

And thus, you can call doSomething with an event handler, and pass in an extra parameter and still access the rest of the object. You could also extend the `MyClassDoSomethingClickHandler` and `MyClass.doSomething` so that it passes through the event data as well, if you require it.

I’m still working on SVGForm, and I have the start of a focus model, text input control, and I’ve now started on a Menu control. Once the menu works, there’ll be another update.

I’ve passed the “magic” 1,000 lines mark with the code, now. I haven’t coded so much ECMAScript/JavaScript for a single project in my life - my previous record was half that.

[ael]: http://developer.mozilla.org/en/docs/DOM:element.addEventListener