panthro
panthro

Reputation: 24059

The correct way to bind this?

I'm trying to access 'this' inside a method that is called from a button press, where this refers to both the class and the button pressed:

p.myVar = 'banana';

$('.go').on('click', this._init);

p._init = function(e){
    //get the button pressed
    //get this.myVar
};

To do this I bind this:

$('.go').on('click', this._init.bind(this));

The above works and I can now access my var via:

this.myVar; //banana

But I can no longer access the button.

How can I access it, use e.currentTarget or is there a better way?

Upvotes: 0

Views: 69

Answers (2)

nepeo
nepeo

Reputation: 509

I presume your declaring the event listener in a closure, if so you can use a local variable and pass it that, the reference is unique to the closure and can be accessed by the function in the listener when it is called. It becomes a kind of invisible global, the reference only exists to that specific call and the listener function but is still shared.

function initButtons(){
var selfRef = this;
$('.go').on('click',selfRef._init);
}

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382274

You should use the data argument :

$('.go').on('click', {myVar:'banana'}, this._init);

p._init = function(e){
    // use e.data.myVar;
    // this is the right matching clicked element
};

Upvotes: 2

Related Questions