Skip to content

Instantly share code, notes, and snippets.

@toanalien
Created January 7, 2016 05:50
Show Gist options
  • Save toanalien/bfe24402c45dc842115d to your computer and use it in GitHub Desktop.
Save toanalien/bfe24402c45dc842115d to your computer and use it in GitHub Desktop.
demo node event emitter
/*
* app.js
* @toanalien
*/
var Emitter = require('./emitter');
var emtr = new Emitter();
emtr.on('sayhello', function() {
console.log('hello world !');
});
emtr.on('sayhello', function() {
console.log('hello everybody !');
});
console.log('demo node event emitter');
emtr.emit('sayhello');
/*
* output
* demo node event emitter
* hello world !
* hello everybody !
*/
/*
* emitter.js
* @toanalien
*/
function Emitter() {
this.events = {}; // khoi tao doi tuong events
}
Emitter.prototype.on = function(type, listener) {
this.events[type] = this.events[type] || []; // neu properties events[type] chua ton tai, khoi tao arr events[type]
this.events[type].push(listener); // them listener vao arr
}
Emitter.prototype.emit = function(type) {
if (this.events[type]) { // kiem tra su ton tai cua properties events[type]
this.events[type].forEach(function(listener) {
listener(); // goi listener
});
}
}
module.exports = Emitter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment