最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Preserve 'this' with jQuery.bind? - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

4 Answers 4

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(); }); 
发布评论

评论列表(0)

  1. 暂无评论