Created
October 5, 2017 13:30
-
-
Save kareniel/bda3ab6707fa643c6ed7c11fd901739d to your computer and use it in GitHub Desktop.
Minimal event emitter implementation
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
module.exports = Emitter | |
function Emitter () { | |
if (!(this instanceof Emitter)) return new Emitter() | |
this._listeners = {} | |
} | |
Emitter.prototype.emit = function (eventName, data) { | |
const listeners = this._listeners[eventName] | |
if (listeners && listeners.length > 0) { | |
for (let i = 0; i < listeners.length; i++) { | |
const listener = listeners[i] | |
listener(data) | |
} | |
} | |
} | |
Emitter.prototype.on = function (eventName, listener) { | |
if (!this._listeners[eventName]) this._listeners[eventName] = [] | |
this._listeners[eventName].push(listener) | |
} | |
Emitter.prototype.off = function (eventName, listener) { | |
const listeners = this._listeners[eventName] | |
if (!listeners) return | |
const index = listeners.indexOf(listener) | |
if (index !== -1) { | |
this._listeners[eventName].splice(index, 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment