I believe the reason because you want to do that, it's to keep this
pointing to your object instance, instead of document, is that correct?
In this case, you can actually do several thing.
1) Just store the reference of the function in your object:
class Dragable {
constructor(gameObject) {
this._listener = (mouseEvent) => this.click(mouseEvent);
document.addEventListener('mousedown', this._listener)
}
click(mouseEvent) {
console.log("Clicking..");
//Remove eventhandler by reference.
}
destroy() {
document.removeEventListener('mousedown', this._listener)
}
}
Also, if you're in a module, you can encapsulate _listener
as private symbol in order to do not make it accessible easily from the outside.
2) Use a static "click" handler, then you bound to the instance:
class Dragable {
constructor(gameObject) {
this.click = Dragable.click.bind(this);
document.addEventListener('mousedown', this.click)
}
static click(mouseEvent) {
console.log("Clicking..");
//Remove eventhandler by reference.
}
destroy() {
document.removeEventListener('mousedown', this.click)
}
}
(You could also avoid static and just have this.click = this.click.bind(this)
but I don't like overriding like that, but that's a personal taste)
3) You can use an event handler object instead of a function:
class Dragable {
constructor(gameObject) {
document.addEventListener('mousedown', this);
}
handleEvent(mouseEvent) {
console.log("Clicking..");
//Remove eventhandler by reference.
}
destroy() {
document.removeEventListener('mousedown', this)
}
}
Using handleEvent
, inside this.click
the this
will point to your object instance and not document: notice that if you have multiple events to subscribe, you have to use a switch(event.type)
to delegate to the right method. More info about it: https://developer.mozilla.org/en-US/docs/Web/API/EventListener/handleEvent