Better way to maintain this reference on event listener functions

Bob Myers rtm at gol.com
Mon May 9 17:10:11 UTC 2016


I'm confused by this whole thread. There is nothing here that cannot be
handled easily by a minimal amount of user glue code, to give just one
example:

```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();
```

To remove after one call:

```js
function listenOnce(element, type, handler) {
  function _handler(e) {
    handler(e);
    element.removeEventListener(type, _handler);
  }
  element.addEventListener(type, _handler);
}
```

If you want to more easily use the same handler on multiple elements:

```
function makeHandler(type, handler) {
  return {
    listen(elt) { elt.addEventListener(type, handler) },
    unlisten(elt) { elt.removeEventListener(type, handler); }
  };
}

var handler = makeHandler('click', e => handleIt(e));
handler.listen(elt);
handler.unlisten(elt);
```

There are other useful possibilities opened up by using the `EventListener`
interface. None of this requires any change to `addEventListener` signature
as far as I can tell.

And so on.

Bob

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

> Haha, no problem, Andrea. I think I may have not explained the scenario as
> clearly in my original post so I apologize for that. But like Boris
> mentioned, removing the event listeners in a much easier way is also a part
> of my goal here.
>
> I do like passing context in an argument and if using the third argument
> is a possibility, that would be nice. I would vote for:
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160509/1306eff9/attachment.html>


More information about the es-discuss mailing list