Better way to maintain this reference on event listener functions

Andrea Giammarchi andrea.giammarchi at gmail.com
Mon May 9 10:04:42 UTC 2016


This is rather about DOM land, nothing to do with EcmaScript standard.

I'll quickly answer but please bear in mind this mailing list is about ES,
not about WHATWG or W3C, thanks.

Since DOM Level 3 has been available (every browser compatible with
addEventListener, polyfilled for IE8 too if necessary [1] )

```js
// generic handler: any class, any object
function handleEvent(e) {
  this['on' + e.type](e);
};

// as class
function SomeClass(someNode) {
  someNode.addEventListener('click', this);
}
SomeClass.prototype.onclick = function () {
  alert('clicked');
};
SomeClass.prototype.handleEvent = handleEvent;

// as object
document.body.addEventListener('click', {
  name: 'runtime',
  onclick: function () {
    alert(this.name);
  },
  handleEvent: handleEvent
});


// as utility [2]
Handler.add('body', {
  name: 'utility',
  click: function () { alert('clicked ' + this.name); }
});
```

The advantage is that not only you don't need to store a reference and
create a bound version of each method,
you can also always remove the listener later on whenever is needed.

```js
// class example
someNode.removeEventListener('click', this);
```

As long as you have a listener able to drop the handler [3]

Best Regards

[1] https://github.com/WebReflection/ie8
[2] https://github.com/WebReflection/dom-handler
[3]
https://www.webreflection.co.uk/blog/2015/10/22/how-to-add-dom-events-listeners#-and-about-that-this-reference-


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

> Sorry if I've missed any previous requests for this feature, but is there
> any goal to allow callbacks passed to event listeners to keep their `this`
> context without having to store a reference to the this-binded event
> listener first?
>
> I frequently find myself doing this in my class methods:
>
> ```javascript
> this.el = document.createElement('div');
> this.listener = this.onClick.bind(this); // store a reference just to bind
> the `this`
> this.el.addEventListener('click', this.listener)
> ```
>
> only to ensure the correct listener mapping gets removed later on in a
> `destroy`-like function with this code:
>
> ```javascript
> this.el.removeEventListener('click', this.listener);
> ```
>
> A few years ago I would've never thought of a good reason to add such
> sugar, but now that JS is moving forward with class declarations, it seems
> more warranted now.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160509/8a58ff41/attachment-0001.html>


More information about the es-discuss mailing list