Better way to maintain this reference on event listener functions

Bob Myers rtm at
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

function listen(element, type, handler) {
  element.addEventListener(type, handler);
  return function() {
    element.removeEventListener(type, handler);

var unlisten = listen(myElement, 'click', e => this.handler(e));

To remove after one call:

function listenOnce(element, type, handler) {
  function _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));

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.


On Mon, May 9, 2016 at 10:26 PM, Mark Kennedy <mkay581 at> 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: <>

More information about the es-discuss mailing list