首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Vanilla JavaScript中的事件处理程序命名空间

Vanilla JavaScript中的事件处理程序命名空间
EN

Stack Overflow用户
提问于 2014-02-17 06:10:33
回答 3查看 19.1K关注 0票数 41

我熟悉jQuery的事件处理程序中的名称空间。我可以在特定的名称空间中添加事件处理程序:

代码语言:javascript
复制
$('#id').on('click.namespace', _handlerFunction);

然后我可以删除该名称空间中的所有事件处理程序:

代码语言:javascript
复制
$('#id').off('.namespace');

这样做的好处是,我只能删除此名称空间中的事件,而不能删除应该维护的任何用户添加的/附加的事件。

有没有人有什么建议,告诉我如何不使用jQuery,却能达到类似的效果?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-02-17 06:25:01

我想你在找addEventListenerremoveEventListener。您还可以定义自定义事件并使用dispatchEvent触发它们。

但是,要删除事件侦听器,您需要保留对事件函数的引用,以便只删除要删除的函数,而不是清除整个事件。

票数 12
EN

Stack Overflow用户

发布于 2017-06-08 11:31:45

对于任何还在寻找它的人,我最终做了一个帮助程序单例,它为我跟踪函数引用。

代码语言:javascript
复制
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:

代码语言:javascript
复制
EventHandler.addEventListener('keydown.doop', () => console.log("Doop"));
EventHandler.addEventListener('keydown.wap', () => console.log("Wap"));
EventHandler.removeEventListener('keydown.doop');
// keydown.wap is still bound
票数 37
EN

Stack Overflow用户

发布于 2017-06-08 17:36:52

在这个解决方案中,我扩展了DOM,使其具有能够使用事件命名空间的onoff方法:

代码语言:javascript
复制
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)
代码语言:javascript
复制
Click anywhere 

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21817397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档