Created
March 18, 2015 19:43
-
-
Save ThiagoMiranda/093bcafcbc10d55410d2 to your computer and use it in GitHub Desktop.
Eventbus
This file contains 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
var EventBusClass = {}; | |
EventBusClass = function() { | |
this.listeners = {}; | |
}; | |
EventBusClass.prototype = { | |
addEventListener: function(type, callback, scope) { | |
var args = [] | |
var numOfArgs = arguments.length; | |
for(var i=0; i<numOfArgs; i++) { | |
args.push(arguments[i]); | |
} | |
args = args.length > 3 ? args.splice(3, args.length - 1) : []; | |
if(typeof this.listeners[type] != "undefined") { | |
this.listeners[type].push({scope: scope, callback: callback, args: args}); | |
} else { | |
this.listeners[type] = [{scope:scope, callback:callback, args:args}]; | |
} | |
}, | |
removeEventListener: function(type, callback, scope) { | |
if(typeof this.listeners[type] != "undefined") { | |
var numOfCallbacks = this.listeners[type].length; | |
var newArray = []; | |
for(var i=0; i<numOfCallbacks; i++) { | |
var listener = this.listeners[type][i]; | |
if(listener.scope == scope && listener.callback == callback) { | |
} else { | |
newArray.push(listener); | |
} | |
} | |
this.listeners[type] = newArray; | |
} | |
}, | |
dispatch: function(type, media){ | |
var numOfListeners = 0; | |
var event= { | |
type: type, | |
media: media | |
}; | |
var args = []; | |
var numOfArgs = arguments.length; | |
for(var i=0;i<numOfArgs;i++) { | |
args.push(arguments[i]); | |
} | |
args = args.length > 2 ? args.splice(2, args.length - 1) : []; | |
args = [event].concat(args); | |
if(typeof this.listeners[type] != "undefined") { | |
var numOfCallbacks = this.listeners[type].length; | |
for(var i=0; i<numOfCallbacks; i++) { | |
var listener = this.listeners[type][i]; | |
if(listener && listener.callback) { | |
var concatArgs = args.concat(listener.args); | |
listener.callback.apply(listener.scope, concatArgs); | |
numOfListeners += 1; | |
} | |
} | |
} | |
} | |
}; | |
var EventBus = new EventBusClass(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment