Better way to maintain this reference on event listener functions

Mark Kennedy mkay581 at
Mon May 9 09:29:42 UTC 2016

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:

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:

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list