[Javascript] removeEventListener

发布时间 2023-07-27 15:19:09作者: Zhentiw

Mistake 1: Not using the same function reference

// Wrong
button.addEventListener('click', () => {console.log('click')})
button.removeEventListener('click', () => {console.log('click')}) // Won't remove the listener
// correct
const onClick = () => console.log('click')
button.addEventListener('click', onClick)
button.removeEventListener('click', onClick)

// Wrong
button.addEventListener('click', function onClick() {console.log('click')})
button.removeEventListener('click', function onClick() {console.log('click')}) // Won't remove the listener
// correct
function onClick() {console.log('click')}
button.addEventListener('click', onClick)
button.removeEventListener('click', onClick)

 

Mistake 2: not passing the same options

function onClick() {console.log('click')}
button.addEventListener('click', onClick, {capture: true})
button.removeEventListener('click', onClick) // Won't remove, it uses defautl capture: false

 

Helper method:

export default function bind(
   target,
   {type, listener, options}
) {
   target.addEventListener(type, listener, options)
    
   return function unbind() {
       target.removeEventListener(type, listener, options)
   } 
}

// usage
const unbind = bind(button, {
    type: 'click',
    listener: () => console.log('click'),
    options: {capture: true}
});

unbind()

 

Lib: https://github.com/alexreardon/bind-event-listener/tree/master