admin管理员组文章数量:1332604
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(); });
本文标签: javascriptPreserve 39this39 with jQuerybindStack Overflow
版权声明:本文标题:javascript - Preserve 'this' with jQuery.bind? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742264947a2443212.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论