views:

539

answers:

1

I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using JQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to.

In more detail, say I have a "class" as follows:

function Car(owner) {
  this.owner = owner;
}
Car.prototype = {
  drive: function() {
    alert("Driving "+this.owner+"s car!");
  }
}

And an instance:

var myCar = new Car("Bob");

I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class".

Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods".

function createHandler( obj, method ) {
  return function( event ) {
    return obj[method](event||window.event);
  }
}

I've used it as follows:

document.getElementById("myButton")
  .addEventListener("click", createHandler(myCar,"drive"));

How do I accomplish something like this with JQuery?

I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.

+5  A: 

Just use an anonymous function:

$("#myButton").click(function() { myCar.drive(); });
Jim
this will work only for one instance. if there multiple instances of Car, it won't work.
sonofdelphi