Created
May 25, 2017 14:39
-
-
Save tejpratap46/1ae9ac86acbdbb4e9a7d49738cb1715b to your computer and use it in GitHub Desktop.
A singleton class to manage events (pus-sub)
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
// A singleton class to manage events (pus-sub) | |
let eventManagerInstance = null; | |
export default class Event { | |
constructor(){ | |
if (!stateManagerInstance) { | |
stateManagerInstance = this; | |
this.events = {}; | |
} | |
return eventManagerInstance; | |
} | |
on(eventName, fn) { | |
this.events[eventName] = this.events[eventName] || []; | |
this.events[eventName].push(fn); | |
} | |
off(eventName, fn) { | |
if (this.events[eventName]) { | |
for (var i = 0; i < this.events[eventName].length; i++) { | |
if (this.events[eventName][i] === fn) { | |
this.events[eventName].splice(i, 1); | |
break; | |
} | |
}; | |
} | |
} | |
trigger(eventName, data) { | |
if (this.events[eventName]) { | |
this.events[eventName].forEach(function(fn) { | |
fn(data); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment