krb
krb

Reputation: 16325

Preserve 'this' with jQuery.bind?

I want to bind an event to a jQuery element so it calls a function in my class, but when the function gets called, this variable no longer points to the class, instead pointing to the sender element.

this.remove = function() {
    alert(this); 
    /* Shows [object HTMLImageElement] instead of the desired class */
    this.dv.remove(); /* error */
}

$(this.buttons['cancel']).bind("click", this.remove);

How can I get around that?

Upvotes: 3

Views: 872

Answers (4)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Use jQuery proxy to preserve the context.

this.remove = function() {
    alert(this); 
    /* Shows [object HTMLImageElement] instead of the desired class */
    this.dv.remove(); /* error */
}

//Now in the click handler this will point to the context which we pass in $.proxy
$(this.buttons['cancel']).bind("click", $.proxy(this.remove, this));

Upvotes: 1

J. Holmes
J. Holmes

Reputation: 18546

$(this.buttons['cancel']).bind("click", $.proxy(this.remove, this));

Where the second argument is the context that you want the method to execute in.

Upvotes: 8

Jordão
Jordão

Reputation: 56477

You need to call it inside a function, just using this.remove won't have the desired effect. And, you have to capture this in a different variable, because it will change inside the function:

var self = this;
$(this.buttons['cancel']).bind("click", function () { self.remove(); }); 

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

Just put the correct this in a closure:

var that = this;

this.remove = function() {
    alert(that); 
    that.dv.remove();
}

$(this.buttons['cancel']).bind("click", this.remove);

Upvotes: 4

Related Questions