Created
July 21, 2016 08:21
-
-
Save nickylimjj/bf6bfeea72c202288db9283169659a68 to your computer and use it in GitHub Desktop.
Nodejs: understanding Events and Emitters
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
// 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 |
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
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