fireEvent: function(event){
var type = event.type;
if(!this.events) return;
var listeners = this.events.get(type);//Listeners is an array of {func:[function],scope:[object]}
var listener;
if(listeners != null){
for(var i = 0,listener; listener = listeners[i++];){
console.info(listener);//show the function and the scope
//Using timeout, so the handlers may be execute "simultaneously"
window.setTimeout(function handler(){
console.info(listener);//shows undefined on console
listener.func.apply(listener.scope, [event]);
},0);
}
}
},
Refactorings
No refactoring yet !
paul.wilkins.myopenid.com
September 8, 2009, September 08, 2009 15:04, permalink
When the timeout runs the handler, the handler function is run from the scope of the window object.
You need the handler function to know about the listener object. You can do that by passing listener to a function, and then have that function return a function. That way the returned function will still know about the listener variable.
The same goes for the event variable as well.
fireEvent: function(event) {
var type = event.type;
if (!this.events) return;
var listeners = this.events.get(type);
var listener;
if (listeners != null) {
for (var i = 0,listener; listener = listeners[i++];) {
// Using timeout, so the handlers may be execute "simultaneously"
window.setTimeout(function (listener, event) {
return function handler() {
listener.func.apply(listener.scope, [event]);
};
}(listener, event), 0);
}
}
},
Mikhas
September 8, 2009, September 08, 2009 16:26, permalink
I got it just by declaring the "listener" variable outside the for loop
fireEvent: function(event){
var type = event.type;
if(!this.events) return;
var listeners = this.events.get(type);
if(listeners != null){
var listener;
for(var i = 0; i < listeners.length;i++){
listener = listeners[i];
//Using timeout, so the handlers may be execute simultaneously
window.setTimeout(function handler(){
listener.func.apply(listener.scope, [event]);
},0);
}
}
}
This code used to works fine.