Tuesday, September 17, 2013

Event manager - this undefined in callback function

Event manager - this undefined in callback function

I am trying to create a custom javascript EventManager class and add some
callback functions. But when the callback function is called, the 'this'
object in the function is undefined. I looked at Custom Javascript
EventManager - please help me complete, but this doesn't answer my
questions completely.
Why is this and this.name undefined in this.onEvent? Please help, thank you.
Here is my jsfiddle: http://jsfiddle.net/Charissima/fswfv/3/
function arEventManager() {
this.callbacks = {};
this.addCallback = function(eventCategory, fn) {
if (!this.callbacks[eventCategory]) {
this.callbacks[eventCategory] = [];
}
if (fn instanceof Function) {
this.callbacks[eventCategory].push(fn);
}
return this;
}, // addCallback
this.dispatchEvent = function(eventCategory, params) {
// Callback-Funktion(en) ausloesen
for (var iC = 0, lC = this.callbacks[eventCategory].length; iC <
lC; iC++) {
console.log( this.callbacks[eventCategory][iC] );
this.callbacks[eventCategory][iC](params);
}
} // dispatchEvent
};
function arPerson() {
this.name;
this.setName = function(name) {
this.name = name;
},
this.getName = function() {
return (this.name);
},
this.onEvent = function(p2) {
alert('this.name = ' + this.name + ' / ' + 'p2.name = ' + p2.name);
}
};
var eventManager = new arEventManager;
var Thomas = new arPerson();
Thomas.setName('Thomas');
var Mike = new arPerson();
Mike.setName('Mike');
eventManager.addCallback("myEvent", Mike.onEvent);
function test() {
eventManager.dispatchEvent('myEvent', Thomas);
}

No comments:

Post a Comment