Does jQuery off method remove event listeners added with addEventListener?

谁说胖子不能爱 提交于 2020-01-02 07:22:09

问题


I am working on an old code and I have seen in the code that there are many events added with javascript addEventListener and some added with jQuery.on() on the same element but in the detach method it is used only jQuery.off() to remove them. So I was wondering if this code will work as the guys that wrote it expected (to remove all events from the dom element) or the events added with javascript won't be removed.


回答1:


It does not.

If you investigate the native removeEventListener api you can see that it expects the original callback for a successful removal. As far as I'm aware, there is no native way for removing all event listeners on a node.

jQuery acts as an intermediary for much of what it does. It does this so that it can maintain control of its api with things like on and off.

This won't be an issue if you write your code in such a way that it tracks adds so that you can later do some kind of cleanup step; however, it does put the onus on you.

Now if all browsers supported getEventListeners as Chrome does this could be a different story. Read this for an understanding of why this is not desirable.



来源:https://stackoverflow.com/questions/41715451/does-jquery-off-method-remove-event-listeners-added-with-addeventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!