Skip to content

Instantly share code, notes, and snippets.

@pjchender
Last active May 22, 2017 14:13
Show Gist options
  • Save pjchender/edef520076b07a27089a3a74b4fb6251 to your computer and use it in GitHub Desktop.
Save pjchender/edef520076b07a27089a3a74b4fb6251 to your computer and use it in GitHub Desktop.
[Node][Unit33] 模擬 Event Emitter
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')
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