What is the best way to add and remove event listeners?

Topics: General
Nov 13, 2012 at 7:44 PM

Here is how we currently create an event listener:

this._domElement.addEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), false);

Which is fine, it works perfectly well and the events fire and are all in local scope.

However we then can't remove the event listener. Neither this:

this._domElement.removeEventListener('mousedown', this.onMouseDown, false);

nor this:

this._domElement.removeEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), false);

.. works, despite the signature matching. Probably because in the resulting JavaScript it seems to create an anonymous function.

What is the recommended way to add/remove an event listener from within TypeScript?

Nov 14, 2012 at 4:00 PM

Generally for all questions like this, the answer is "do it the same as you would in JavaScript".  In this particular case, a solution might look something like this:


class Greeter {
    _element: HTMLElement;

    constructor (element: HTMLElement) { 
        this._element = element;
        this.onMouseDown = <any>this.onMouseDown.bind(this);
        this._element.addEventListener('mousedown', this.onMouseDown);

    onMouseDown() {
        this._element.innerText = Math.random().toString();
        this._element.removeEventListener('mousedown', this.onMouseDown);


new Greeter(document.body)

This uses a .bind to fix the 'this' type of the callback function object and store back onto the instance so it can be used later.

Note that the "<any>" type assertion is no longer needed here in current 'develop' branch and upcoming 0.8.1 release.

Nov 14, 2012 at 9:49 PM

As a side note, if you want DOM-less event dispatching, I wrote a tiny library to provide that functionality. It is available on GitHub: EventDispatcher-ts.

With that library, your class can just extend EventDispatcher. Enjoy!