我创建了一个名为 SearchBox 的类来处理搜索交互(延迟触发、按 Enter 键时搜索、在活动时阻止搜索、在搜索完成且文本已更改时同步结果等)。
所有的类方法都是原型方法,意味着可以通过this
. 在下面的代码中,假设p
是类的原型。
p.registerListeners = function () {
$(this.element).on('keypress', this.searchKeyPressed);
};
p.unregisterListeners = function () {
$(this.element).off('keypress', this.searchKeyPressed);
};
这不起作用,因为当 keypress 事件调用searchKeyPressed
处理程序时,它不会在this
. 我能想到的唯一解决方案是只有现代浏览器支持的解决方案,即将回调绑定到this
,这实际上创建了一个新函数。由于它创建了一个新函数,因此我必须缓存它以便稍后将其删除,因为我必须将相同的引用off
传递给我传递给on
.
有没有比这更好的方法,或者这样可以吗?
var boundKeyPressed;
p.registerListeners = function () {
boundKeyPressed = this.searchKeyPressed.bind(this);
$(this.element).on('keypress', boundKeyPressed);
};
p.unregisterListeners = function () {
$(this.element).off('keypress', boundKeyPressed);
};
我认为这可能jQuery.on
会提供一种自动执行此事件绑定的方法,但它似乎绑定this
到不同的事物,具体取决于它的调用方式。例如,当使用时on('eventname',instance.func)
,this
是“currentTarget”(在冒泡术语中不一定是“目标”),而当使用时on('eventname','selector',instance.func)
,this
是指匹配选择器的元素。在任何一种情况下,func
运行都好像与 没有关系instance
。