function bubble(content, triggerElm){
this.element = $('<div class="bubble" />').html(content);
this.element.css(.....) // here is positioned based on triggerElm
}
bubble.prototype.show = function(){
$(document).on('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype.hide = function(){
$(document).off('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype._click = function(event){
console.log('click', this);
if(this.element.is(event.target) || (this.element.has(event.target).length > 0))
return true;
this.hide();
};
var b = new bubble();
b.show();
b.hide();
我一直在控制台中看到点击,所以点击并没有解除绑定(bind)。
但是,如果我删除 bind()
调用,点击就会解除绑定(bind)。有谁知道为什么?我需要一种能够在我的测试函数中更改“this”的方法,这就是我使用 bind()
的原因。
最佳答案
问题在于 this._click.bind()
每次调用时都会创建一个新函数。为了分离特定的事件处理程序,您需要传入用于创建事件处理程序的原始函数,但此处不会发生这种情况,因此不会删除处理程序。
如果您的应用程序中只有几个气泡
,您可以并且根本不使用this
。这将消除很多关于 this
指的是什么的混淆,并确保每个 bubble
保留对其自己的 click
函数的引用,该函数可以用于根据需要删除事件:
function bubble(content, triggerElm) {
var element = $('<div class="bubble" />').html(content);
element.css(.....); // here is positioned based on triggerElm
function click(event) {
console.log('click', element);
if (element.is(event.target) ||
element.has(event.target).length > 0) {
return true;
}
hide();
}
function show() {
$(document).on('click', click);
element.css(....);
}
function hide() {
$(document).off('click', click);
element.css(....);
}
return {
show: show,
hide: hide
};
}
var b1 = bubble(..., ...);
b1.show();
var b2 = bubble(..., ...);
b2.show();
看看这如何让您免于使用诸如 .bind()
和下划线前缀方法之类的发明。
关于javascript - jQuery off() 在使用 bind 时不是取消绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800850/