54aceba7df836ea9396d6a14cc2f19c0

This code used to works fine.

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 !

Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

September 8, 2009, September 08, 2009 15:02, permalink

No rating. Login to rate!

[deleted]

Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

September 8, 2009, September 08, 2009 15:04, permalink

No rating. Login to rate!

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);
        }
    }
},
54aceba7df836ea9396d6a14cc2f19c0

Mikhas

September 8, 2009, September 08, 2009 16:26, permalink

No rating. Login to rate!

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);
			}
		}
	}

Your refactoring





Format Copy from initial code

or Cancel