Created
February 14, 2014 01:46
-
-
Save notdol/8994388 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Polyfill EventEmitter. */ | |
var Queue = function () { | |
this.events = {}; | |
this.queue = []; | |
this.methodStr; | |
this.current; | |
}; | |
Queue.prototype.setMethod = function(methodStr){ | |
this.methodStr = methodStr; | |
} | |
Queue.prototype.add = function(t){ | |
var self = this; | |
// prevent same object | |
for(var i = 0 ; i < this.queue; i ++){ | |
if(t == this.queue[i]){ | |
return ; | |
} | |
} | |
t['__'+this.methodStr] = t[this.methodStr]; | |
t[this.methodStr] = function(){ | |
var args = Array.prototype.slice.call(arguments); | |
self.queue.push({obj : t, params : args}); | |
self.start(); | |
}; | |
t['__queueComplete'] = function(){ | |
if( self.current == t){ | |
self.current = undefined; | |
self.start(); | |
} | |
}; | |
} | |
Queue.prototype.start = function(){ | |
var self = this; | |
if(this.current){ | |
}else{ | |
var t = this.queue.shift(); | |
if(t){ | |
self.current = t.obj; | |
t.obj['__'+this.methodStr].apply(t.obj,t.params); | |
} | |
} | |
} | |
Queue.prototype.on = function (event, listener) { | |
if (typeof this.events[event] !== 'object') { | |
this.events[event] = []; | |
} | |
this.events[event].push(listener); | |
}; | |
Queue.prototype.off = function (event, listener) { | |
var idx; | |
if (typeof this.events[event] === 'object') { | |
idx = indexOf(this.events[event], listener); | |
if (idx > -1) { | |
this.events[event].splice(idx, 1); | |
} | |
} | |
}; | |
Queue.prototype.emit = function (event) { | |
var i, listeners, length, args = [].slice.call(arguments, 1); | |
if (typeof this.events[event] === 'object') { | |
listeners = this.events[event].slice(); | |
length = listeners.length; | |
for (i = 0; i < length; i++) { | |
listeners[i].apply(this, args); | |
} | |
} | |
}; | |
Queue.prototype.once = function (event, listener) { | |
this.on(event, function g () { | |
this.off(event, g); | |
listener.apply(this, arguments); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment