Last active
June 30, 2016 20:13
-
-
Save mkozhukharenko/c8c4c651864adb5fcea5fbaac4cbcde8 to your computer and use it in GitHub Desktop.
Simple Event Emitter
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
// 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); | |
}); | |
}; | |
} |
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
// 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