Better way to maintain this reference on event listener functions

Bob Myers rtm at gol.com
Mon May 9 17:30:21 UTC 2016


Yes, you are missing something. This code will absolutely remove it the
handler, because the handler being passed to both `addEventListener` and
`removeEventListener is identical (in the `===` sense).

On Mon, May 9, 2016 at 10:50 PM, Mark Kennedy <mkay581 at gmail.com> wrote:

> Thanks, Bob. Unless I'm missing something, this code you wrote will not
> remove the event listener when `unlisten` is called. Check out [this
> answer](http://stackoverflow.com/a/30448329/2810742) on stackoverflow.
>
> ```js
> function listen(element, type, handler) {
>   element.addEventListener(type, handler);
>   return function() {
>     element.removeEventListener(type, handler);
>   };
> }
>
> var unlisten = listen(myElement, 'click', e => this.handler(e));
>
> unlisten();
> ```
> --
>
> mark
>
> Sent while riding a hoverboard...
> heyimmark.com :)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160509/0371891a/attachment-0001.html>


More information about the es-discuss mailing list