Question

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.

Was it helpful?

Solution

Just use an anonymous function:

$("#myButton").click(function() { myCar.drive(); });

OTHER TIPS

Try this :

$("#myButton").each(function() {

var $btn = $(this);

    $btn.on('click',function(){

     // Do whatever you want.

    });
});

Here you first create a loop to target all #myButton elements (Which is wrong in your example, You should be using Class instead) like:

$(".myButton").each(...

Then we attach the click event handler to all of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top