I have a problem with eventlisteners in javascript that is probably due to my incomplete control of the language.
I wish to register event listeners using addEventListener() / attachEvent(); I also want to be able to remove the listeners later on, so I can’t register anonymous functions.
Say I now want to register a method of an object as an event listener. First I’d expected addEventListener(event, node, object.method) to work. However, after reading up on events I now understand that the this keyword will refer to the event target when the event listener is called, not my object.
To work around this, I have created a new method, methodCallback of the object, like so:
object.methodCallback = function () {
self.method();
}
the self variable is set to copy this in the object constructor. I then register object.methodCallback as an eventlistener.
I feel this must be the wrong way to do it. But what is the right way?
I apologize if this question is common, but I haven’t been able to find an answer on SO so far
It’s common for people to use self in such a way. I would say use ‘self’ if you are within a class and ‘that’ if not.
You need to define self / that one level up in the scope chain.
And yep, that’s the way it rolls. Unfortunately.