Last active
May 22, 2017 14:13
-
-
Save pjchender/edef520076b07a27089a3a74b4fb6251 to your computer and use it in GitHub Desktop.
[Node][Unit33] 模擬 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
const Emitter = require('./emitter') | |
let emtr = new Emitter() | |
emtr.on('greet', function () { | |
console.log('Somewhere, someone said hello') | |
}) | |
emtr.on('greet', function () { | |
console.log('A greeting occurred') | |
}) | |
console.log('Hello') | |
emtr.emit('greet') |
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
function Emitter () { | |
this.events = {} | |
} | |
Emitter.prototype.on = function (type, listener) { | |
this.events[type] = this.events[type] || [] | |
this.events[type].push(listener) | |
} | |
/* | |
{ | |
'onSaveFile': [function(){}, function(){}] | |
} | |
*/ | |
Emitter.prototype.emit = function (type) { | |
if (this.events[type]) { | |
this.events[type].forEach(listener => { | |
listener() | |
}) | |
} | |
} | |
module.exports = Emitter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment