Reputation: 894
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
Upvotes: 2
Views: 2915
Reputation: 7944
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.
var self = this;
object.methodCallback = function () {
self.method();
}
And yep, that's the way it rolls. Unfortunately.
Upvotes: 2
Reputation: 21343
Reassigning "this scope" so you could reference it later is an acceptable behavior in Javascript as you would probably need it later. Javascript library such as jQuery and YUI provides you an easy to use function (such as $.proxy() in jQuery or YUI.bind()) to do that. Given that they provide you such function, I am guessing that this is a common method in JS
Upvotes: 0