Created
October 17, 2017 14:55
-
-
Save KleoPetroff/55ba86290659d856baaa848d09aa0844 to your computer and use it in GitHub Desktop.
EventBus.js
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
class EventBus { | |
constructor() { | |
this.listeners = {}; | |
} | |
addEventListener(type, callback, scope) { | |
let args = []; | |
const numOfArgs = arguments.length; | |
for(let 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(type, callback, scope) { | |
if (typeof this.listeners[type] != "undefined") { | |
const numOfCallbacks = this.listeners[type].length; | |
const newArray = []; | |
for(let i=0; i<numOfCallbacks; i++) { | |
const listener = this.listeners[type][i]; | |
if(listener.scope === scope && listener.callback === callback) { | |
} else { | |
newArray.push(listener); | |
} | |
} | |
this.listeners[type] = newArray; | |
} | |
} | |
dispatch(type, target) { | |
const event = { | |
type: type, | |
target: target | |
}; | |
let args = []; | |
const numOfArgs = arguments.length; | |
for(let 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") { | |
const listeners = this.listeners[type].slice(); | |
const numOfCallbacks = listeners.length; | |
for(let i=0; i<numOfCallbacks; i++) { | |
let listener = listeners[i]; | |
if (listener && listener.callback) { | |
const concatArgs = args.concat(listener.args); | |
listener.callback.apply(listener.scope, concatArgs); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment