Skip to content

Instantly share code, notes, and snippets.

@nickylimjj
Created July 21, 2016 08:21
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 nickylimjj/bf6bfeea72c202288db9283169659a68 to your computer and use it in GitHub Desktop.
Save nickylimjj/bf6bfeea72c202288db9283169659a68 to your computer and use it in GitHub Desktop.
Nodejs: understanding Events and Emitters
// emitter.js
// returns a Function Constructor
function Emitter () {
this.events = {}
}
// Listener is the code that responds to an event
// analogy: a person taking a cue from an event to execute his task
// @type : type of event. Ie, onClick
// @listener: code to be executed
Emitter.prototype.on = function (type, listener) {
this.events[type] = this.events[type] || []
this.events[type].push(listener)
}
Emitter.prototype.emit = function (type) {
if (this.events[type]) {
this.events[type].forEach(function (listener) {
listener()
})
}
}
module.exports = Emitter
var Emitter = require('./emitter')
var emtr = new Emitter()
emtr.on('greet', function fn1 () {
console.log('Somewhere, someone says hello!')
})
emtr.on('greet', function fn2 () {
console.log('A greeting occurred!')
})
console.log('hello!')
emtr.emit('greet')
/*
* emtr.events = {
* greet: [ fn1, fn2 ]
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment