Created
May 12, 2018 05:10
-
-
Save dead-claudia/7399f86d03342b5be2cd29016f9850f4 to your computer and use it in GitHub Desktop.
Super simple event emitter
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
"use strict" | |
function EventEmitter() { | |
this._events = Object.create(null) | |
} | |
EventEmitter.prototype.on = function (event, func) { | |
var handlers = this._events[event] = this._events[event] || [] | |
if (handlers.indexOf(func) < 0) handlers.push(func) | |
} | |
EventEmitter.prototype.off = function (event, func) { | |
if (this._events[event] == null) return | |
var index = this._events[event].indexOf(func) | |
if (index >= 0) this._events[event].splice(index, 1) | |
} | |
EventEmitter.prototype.emit = function (event) { | |
var handlers = this._events[event] | |
if (handlers == null) return | |
var args = [].slice.call(arguments, 1) | |
for (var i = 0; i < handlers.length; i++) handlers[i].apply(void 0, args) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment