我熟悉jQuery的事件处理程序中的名称空间。我可以在特定的名称空间中添加事件处理程序:
$('#id').on('click.namespace', _handlerFunction);
然后我可以删除该名称空间中的所有事件处理程序:
$('#id').off('.namespace');
这样做的好处是,我只能删除此名称空间中的事件,而不能删除应该维护的任何用户添加的/附加的事件。
有没有人有什么建议,告诉我如何不使用jQuery,却能达到类似的效果?
发布于 2014-02-17 06:25:01
我想你在找addEventListener和removeEventListener。您还可以定义自定义事件并使用dispatchEvent触发它们。
但是,要删除事件侦听器,您需要保留对事件函数的引用,以便只删除要删除的函数,而不是清除整个事件。
发布于 2017-06-08 11:31:45
对于任何还在寻找它的人,我最终做了一个帮助程序单例,它为我跟踪函数引用。
class EventHandlerClass {
constructor() {
this.functionMap = {};
}
addEventListener(event, func) {
this.functionMap[event] = func;
document.addEventListener(event.split('.')[0], this.functionMap[event]);
}
removeEventListener(event) {
document.removeEventListener(event.split('.')[0], this.functionMap[event]);
delete this.functionMap[event];
}
}
export const EventHandler = new EventHandlerClass();
然后只需导入EventHandler并使用like:
EventHandler.addEventListener('keydown.doop', () => console.log("Doop"));
EventHandler.addEventListener('keydown.wap', () => console.log("Wap"));
EventHandler.removeEventListener('keydown.doop');
// keydown.wap is still bound
发布于 2017-06-08 17:36:52
在这个解决方案中,我扩展了DOM,使其具有能够使用事件命名空间的on
和off
方法:
var events = {
on(event, cb, opts){
if( !this.namespaces ) // save the namespaces on the DOM element itself
this.namespaces = {};
this.namespaces[event] = cb;
var options = opts || false;
this.addEventListener(event.split('.')[0], cb, options);
return this;
},
off(event) {
this.removeEventListener(event.split('.')[0], this.namespaces[event]);
delete this.namespaces[event];
return this;
}
}
// Extend the DOM with these above custom methods
window.on = Element.prototype.on = events.on;
window.off = Element.prototype.off = events.off;
window
.on('mousedown.foo', ()=> console.log("namespaced event will be removed after 3s"))
.on('mousedown.bar', ()=> console.log("event will NOT be removed"))
.on('mousedown.baz', ()=> console.log("event will fire once"), {once: true});
// after 3 seconds remove the event with `foo` namespace
setTimeout(function(){
window.off('mousedown.foo')
}, 3000)
Click anywhere
https://stackoverflow.com/questions/21817397
复制相似问题