Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Kristina Brooks Avatar asked May 30 '26 22:05

Kristina Brooks


1 Answers

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

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

like image 179
J. Holmes Avatar answered Jun 02 '26 12:06

J. Holmes