Vanilla JavaScript中的事件处理程序命名空间 [英] Event Handler Namespace in Vanilla JavaScript
问题描述
我熟悉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.
这篇关于Vanilla JavaScript中的事件处理程序命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!