我正在将我的自定义处理程序绑定到keydown
"文档"的事件:
this._bindCloseDlgEvents = function() {
$(document).keydown(closeDlgByEscClick.bind(this));
};
我已经检查过并且事件已绑定:$._data( document, "events" )
返回{keydown: Array[1]}
.现在我正在尝试取消绑定相同的处理程序:
this._unbindCloseDlgEvents = function() {
$(document).off('keydown', closeDlgByEscClick);
};
与$._data( document, "events" )
一起检查 - 没有任何变化{keydown: Array[1]}
.为什么会这样?如果我以这种方式取消绑定$(document).off('keydown')
则事件已取消绑定,但我只需要取消绑定我的特定处理程序。
因为你正在使用.bind()
它返回一个新的匿名函数。
使用命名空间事件处理程序,例如
this._bindCloseDlgEvents = function() {
$(document).on('keydown.closedialogevent', closeDlgByEscClick.bind(this));
};
然后
this._unbindCloseDlgEvents = function() {
$(document).off('keydown.closedialogevent');
};
.bind()
bind() 方法创建一个新函数,该函数在调用时具有其 此关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数前面的参数。
演示:小提琴