I’m a little confused by the way scope changes in event handlers, specifically the way that “this” doesn’t refer to the object the method is originally part of. For example, suppose I’m defining a Layer like this:
var MyLayer = cc.Layer.extend ({
ctor:function () {
this.foo = "bar";
cc.eventManager.addListener({
event:cc.EventListener.CUSTOM,
eventName:"MyEvent",
callback:this.MyHandler},
this);
},
MyHandler:function(event)
{
cc.log(this.foo);
}
});
i can trigger the event fine:
cc.eventManager.dispatchCustomEvent ("MyEvent");
but this.foo is undefined, because “this” doesn’t refer to the MyLayer object anymore, it refers to something else, maybe the event dispatcher? I find this kind of confusing because it cuts the event handlers off from their classes.
I can get around it by accessing the event target:
MyHandler:function(event) {
var self=event._currentTarget;
cc.log(self.foo);
}
But that seems awkward and a little confusing to use this and self in different places. Is this the right way to do this, or is there another convention in cocos?