问题
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