S
S
sanex33392015-09-15 13:31:39
JavaScript
sanex3339, 2015-09-15 13:31:39

How to remove event handler in typescript?

Problem:

window.addEventListener(eventType, event => this._handler(event));
window.removeEventListener(eventType, event => this._handler(event));

private _handler (event) {
    this._blablabla(event.pageX, event.pageY);
}

In this way, the event is attached to window, but not removed.
If done this way
window.addEventListener(eventType, this._handler);
window.removeEventListener(eventType, this._handler);

It works, of course, but the properties and methods of the class will not be available inside the handler through this.
Through
window.addEventListener(eventType, this._handler.bind(this));
window.removeEventListener(eventType, this._handler.bind(this));

doesn't work either.
What is the right way to remove the event handler in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-09-15
@sanex3339

Through this._handler.bind(this)does not work because it Function#bindreturns a new function (and each time is different, i.e.

this._handler.bind(this) !== this._handler.bind(this)
).
Accordingly, you need something like this:
this.boundHandler = this.handler.bind(this);
window.addEventListener(eventType, this.boundHandler);
//...
window.removeEventListener(eventType, this.boundHandler);

Well, of course, you can write some kind of wrapper. For example:
function bound (eventType: string, handler: Function, context: any): Function {
    var boundHandler = handler.bind(context);
    window.addEventListener(eventType, boundHandler);
    return () => window.removeEventListener(eventType, boundHandler);
}

Such a function will return a function that, when called, will unbind the previously bound handler.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question