Created
January 7, 2016 05:50
-
-
Save toanalien/bfe24402c45dc842115d to your computer and use it in GitHub Desktop.
demo node event 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
/* | |
* 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 ! | |
*/ |
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 | |
* @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