Skip to content

Instantly share code, notes, and snippets.

@mkozhukharenko
Last active June 30, 2016 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkozhukharenko/c8c4c651864adb5fcea5fbaac4cbcde8 to your computer and use it in GitHub Desktop.
Save mkozhukharenko/c8c4c651864adb5fcea5fbaac4cbcde8 to your computer and use it in GitHub Desktop.
Simple Event Emitter
// Simple Event emitter realization
class EventEmitter {
constructor() {
// store for handlers
this.events = {};
}
// subscribe
on(name, fn) {
this.events[name] = this.events[name] || [];
this.events[name].push(fn);
};
// fire an event
trigger(name, args) {
this.events[name] = this.events[name] || [];
this.args = args || [];
this.events[name].forEach(function(fn) {
fn.apply(this, args);
});
};
}
// create instance
var emitter = new EventEmitter();
// listening to all 'ringBell' events
emitter.on('ringBell', function(data) {
console.log('Who\'s there?');
console.log('I see you', data.visitor);
});
// firing events 'ringBell'
emitter.trigger('ringBell', [{ visitor: 'Neighbour' }]);
emitter.trigger('ringBell', [{ visitor: 'Angry man' }]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment