Skip to content

Instantly share code, notes, and snippets.

@joshcox
Created April 7, 2017 02:18
Show Gist options
  • Save joshcox/61759a4b7b6d7be5934ed07c6ddc8b87 to your computer and use it in GitHub Desktop.
Save joshcox/61759a4b7b6d7be5934ed07c6ddc8b87 to your computer and use it in GitHub Desktop.
/* Polyfill indexOf. */
var indexOf;
if (typeof Array.prototype.indexOf === 'function') {
indexOf = function (haystack, needle) {
return haystack.indexOf(needle);
};
} else {
indexOf = function (haystack, needle) {
var i = 0, length = haystack.length, idx = -1, found = false;
while (i < length && !found) {
if (haystack[i] === needle) {
idx = i;
found = true;
}
i++;
}
return idx;
};
};
/* Polyfill EventEmitter. */
var EventEmitter = function () {
this.events = {};
};
EventEmitter.prototype.on = function (event, listener) {
if (typeof this.events[event] !== 'object') {
this.events[event] = [];
}
this.events[event].push(listener);
};
EventEmitter.prototype.removeListener = function (event, listener) {
var idx;
if (typeof this.events[event] === 'object') {
idx = indexOf(this.events[event], listener);
if (idx > -1) {
this.events[event].splice(idx, 1);
}
}
};
EventEmitter.prototype.emit = function (event) {
var i, listeners, length, args = [].slice.call(arguments, 1);
if (typeof this.events[event] === 'object') {
listeners = this.events[event].slice();
length = listeners.length;
for (i = 0; i < length; i++) {
listeners[i].apply(this, args);
}
}
};
EventEmitter.prototype.once = function (event, listener) {
this.on(event, function g () {
this.removeListener(event, g);
listener.apply(this, arguments);
});
};
// create an emitter instance
var emitter = new EventEmitter();
// Attach a listener - when this eventName is fired from the emitter, run this function/action
emitter.on("hello", function() {
console.log("world");
});
// And again
emitter.on("hello", function() {
console.log("world1");
});
// Fire the event (AKA tell any listeners that this "thing" happened and run their function/action)
emitter.emit("hello");
// Wait a second before firing the event
setTimeout(function() {
emitter.emit("hello");
}, 1000);
// A Dog class that fires out an event when the speak method is run
function Dog() {
this.speak = function() {
emitter.emit("hello");
};
}
// Create a dog and tell it to speak after a second
setTimeout(function() {
new Dog().speak();
}, 1000);
// Toy version/example of our future state - we'll initialize an instance and pass it into our UI
function State() {
this._emitter = new Emitter();
}
State.prototype.on = function(eventName, fn) {
this._emitter.on(eventName, fn);
};
new State().on("event", function() {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment