Skip to content

Instantly share code, notes, and snippets.

@KleoPetroff
Created October 17, 2017 14:55
Show Gist options
  • Save KleoPetroff/55ba86290659d856baaa848d09aa0844 to your computer and use it in GitHub Desktop.
Save KleoPetroff/55ba86290659d856baaa848d09aa0844 to your computer and use it in GitHub Desktop.
EventBus.js
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