Hacker News new | ask | show | jobs
by thousande 3239 days ago
Today I learned

In general, a good practice is to avoid anonymous functions for the listener else it is not possible to remove the event later.

1 comments

I guess the function could still be anonymous, but you will at least need to keep it assigned to some variable or property name. If you make use of the `handleEvent` pattern that @carussell suggested, you can however avoid having to keep track of all these callback functions since the listener can always be removed by passing `this` a second time:

['click', 'focus', 'blur'].forEach(type => elm.removeEventListener(type, this));