Last active
October 16, 2017 23:38
-
-
Save tohagan/0f45f47b33e2034c34e4acc3f71fbb0b to your computer and use it in GitHub Desktop.
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 = {}; | |
} | |
EventEmitter.prototype = { | |
constructor: EventEmitter, | |
listeners: function(event) { | |
if (!this.events.hasOwnProperty(event)) { | |
return this.events[event] = []; | |
} else { | |
return this.events[event]; | |
} | |
}, | |
on: function (event, fn) { | |
this.listeners(event).push(fn); | |
}, | |
off: function (event, fn) { | |
var listeners = this.listeners(event); | |
var index = listeners.indexOf(fn); | |
if (index > -1) { | |
listeners.splice(index, 1); | |
} | |
}, | |
emit: function () { | |
var args = arguments; | |
var event = args.shift(); | |
var listeners = this.listeners(event); | |
var len = listeners.length; | |
for (var i = 0; i < len; ++i) { | |
listeners[i].apply(null, args); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment