Answer the question
In order to leave comments, you need to log in
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);
}
window.addEventListener(eventType, this._handler);
window.removeEventListener(eventType, this._handler);
window.addEventListener(eventType, this._handler.bind(this));
window.removeEventListener(eventType, this._handler.bind(this));
Answer the question
In order to leave comments, you need to log in
Through this._handler.bind(this)
does not work because it Function#bind
returns a new function (and each time is different, i.e.
this._handler.bind(this) !== this._handler.bind(this)
). this.boundHandler = this.handler.bind(this);
window.addEventListener(eventType, this.boundHandler);
//...
window.removeEventListener(eventType, this.boundHandler);
function bound (eventType: string, handler: Function, context: any): Function {
var boundHandler = handler.bind(context);
window.addEventListener(eventType, boundHandler);
return () => window.removeEventListener(eventType, boundHandler);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question