Created
December 21, 2020 07:24
-
-
Save sina42048/eafc06f0bea9d8822fd313ffe3d2cadd to your computer and use it in GitHub Desktop.
simple event emitter implementation in nodejs
This file contains 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 process = require('process'); | |
function Event() { | |
this.events = []; | |
} | |
Event.prototype.emit = function(eventName) { | |
process.nextTick(() => { | |
const id = this.events.findIndex((event) => event.name === eventName); | |
for (observer of this.events[id].observers) { | |
observer(); | |
} | |
}); | |
} | |
Event.prototype.on = function(eventName, fn) { | |
if (this.events.length) { | |
const id = this.events.findIndex((event) => event.name === eventName); | |
if (id >= 0) { | |
this.events[id].observers.push(fn); | |
} else { | |
this.events.push({ name: eventName, observers: [fn] }); | |
} | |
} else { | |
this.events.push({ name: eventName, observers: [fn] }); | |
} | |
} | |
const e = new Event(); | |
e.emit('Hello'); | |
e.emit('bye'); | |
e.on('Hello' , () => { | |
console.log('Hello There'); | |
e.emit('inside'); | |
}); | |
e.on('Hello' , () => { | |
console.log('Hello Here'); | |
}); | |
e.on('bye', () => { | |
console.log('goodbye'); | |
}); | |
e.on('inside', () => { | |
console.log('emitted from inside'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment