Pao*_*olo 5 jquery this javascript-events
这是使用jQuery在JavaScript中正确绑定和事件到对象方法的方法吗?
我已经设置了一些示例代码,但我关注的部分是注释后的两行" 这样可以吗? "
当然,由于回调是对象的一种方法,我需要保持相同的上下文.
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');
Run Code Online (Sandbox Code Playgroud)
此外,我可能需要从特定功能中解除事件的绑定.
但以下是行不通的......
MyPrototype.prototype.unbindClick = function() {
$(this.sel).off('click', function(evt) {
MyPrototype.prototype.mouseClick.call(this, evt); });
}
myObject2.unbindClick();
Run Code Online (Sandbox Code Playgroud)
请注意,我将内联函数作为事件处理程序传递.
尝试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');
Run Code Online (Sandbox Code Playgroud)
关于问题的更新:
如果您想取消绑定单个事件处理程序,则需要与绑定时使用的处理程序函数完全相同。否则整个事件就失去约束力。您添加到问题中的解决方案都$.proxy无济于事。不过,还是有一些解决方案:
| 归档时间: |
|
| 查看次数: |
15148 次 |
| 最近记录: |