Skip to main content
 首页 » 编程设计

jquery之将对象的方法绑定(bind)到事件的正确方法

2026年07月24日8kerrycode

这是使用 jQuery 在 JavaScript 中正确绑定(bind)和事件到对象方法的方法吗?

我已经设置了一些示例代码,但我关心的部分是注释“这样可以吗?”后面的两行

当然,由于回调是对象的方法,因此我需要上下文保持不变。

function MyPrototype(id) { 
 
    this.id = id; 
    this.sel = '#' + id; 
 
    // *** IS THIS OK? *** 
    $(this.sel).on('click', function(evt) { 
        MyPrototype.prototype.mouseClick.call(this, evt); }); 
} 
 
MyPrototype.prototype.mouseClick = function (evt) { 
 
    // I want to use evt to get info about the event 
    // I want use this to access properties and methods of the instance 
 
    alert(this.id + ' was clicked'); 
} 
 
myObject1 = new MyPrototype('myDiv1'); 
myObject2 = new MyPrototype('myDiv2'); 

此外,我可能会意识到有必要将事件与特定函数解除绑定(bind)。

但是以下内容不起作用...

MyPrototype.prototype.unbindClick = function() { 
 
    $(this.sel).off('click', function(evt) { 
        MyPrototype.prototype.mouseClick.call(this, evt); }); 
} 
 
myObject2.unbindClick(); 

请注意,我传递了一个内联函数作为事件处理程序。

请您参考如下方法:

尝试jQuery.proxy :

function MyPrototype(id) { 
    this.id = id; 
    this.sel = '#' + id; 
 
    // using jQuery.proxy: 
    $(this.sel).on('click', $.proxy(this.mouseClick, this)); 
 
    // or Function.bind: 
    // $(this.sel).on('click', this.mouseClick.bind(this)); 
 
    // or writing it out: 
    /* 
    var self = this; 
    $(this.sel).on('click', function () { 
      return self.mouseClick.apply(self, arguments); 
    }); 
    */ 
} 
 
MyPrototype.prototype.mouseClick = function(evt) { 
 
    // I want to use evt to get info about the event 
    // I want use this to access properties and methods of the instance 
 
    console.log(this.id + ' was clicked'); 
}; 
 
var myObject1 = new MyPrototype('myDiv1'); 
var myObject2 = new MyPrototype('myDiv2'); 

http://jsbin.com/axokuz/1/

<小时 />

关于问题的更新:

如果您想取消绑定(bind)单个事件处理程序,则需要与绑定(bind)时使用的处理程序函数完全相同。否则整个事件就失去约束力。您添加到问题中的解决方案和 $.proxy 都无济于事。不过,有一些解决方案: