Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created May 12, 2018 05:10
Show Gist options
  • Save dead-claudia/7399f86d03342b5be2cd29016f9850f4 to your computer and use it in GitHub Desktop.
Save dead-claudia/7399f86d03342b5be2cd29016f9850f4 to your computer and use it in GitHub Desktop.
Super simple event emitter
"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