zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Remove an Event Listener with removeEventListener

JavaScript with an Event remove listener
2023-09-14 09:00:46 时间

removeEventListener removes an event listener added with addEventListener. However, there are a number of gotchas to watch out for in order to correctly remove an event listener.

Sometime, if you passed third options to addEventListener, but you forgot to pass the same option when calling removeEventListener, the event won't be removed successfully

 

Simple helper:

export default function bind(
  target, {type, listener, options}
) {
    target.addEventListener(
        type,
        listener,
        options,
    );

    return function unbind() {
        target.removeEventListener(
            type,
            listener,
            options,
        );
    }
}