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

2022-01-14 00:00:00 namespaces javascript dom-events

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

I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

$('#id').on('click.namespace', _handlerFunction);

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

And then I can remove all event handlers in that namespace:

$('#id').off('.namespace');

这里的好处是我只能删除这个命名空间中的事件,而不是任何应该维护的用户添加/附加事件.

The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

有没有人有任何关于我如何不能使用 jQuery,但获得类似结果的提示?

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

推荐答案

我想你正在寻找 addEventListener 和 removeEventListener.您还可以定义自定义事件并使用 dispatchEvent 触发它们.

I think you are looking for addEventListener and removeEventListener. You can also define custom events and fire them using dispatchEvent.

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

However, to remove an event listener, you will need to retain a reference to the event function to remove just the function you want to remove instead of clearing the whole event.

相关文章