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?
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?
Share asked Aug 23, 2011 at 16:46 krbkrb 16.3k29 gold badges114 silver badges186 bronze badges4 Answers
Reset to default 8$(this.buttons['cancel']).bind("click", $.proxy(this.remove, this));
Where the second argument is the context that you want the method to execute in.
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);
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));
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(); });