Skip to content

Instantly share code, notes, and snippets.

@amalantony
Last active February 13, 2017 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalantony/1901c99f9967277534f8e53765451dd2 to your computer and use it in GitHub Desktop.
Save amalantony/1901c99f9967277534f8e53765451dd2 to your computer and use it in GitHub Desktop.
/*
Create an eventEmitter, which has methods "on" and "emit" with the following function signatures.
*/
var EventEmitter = {
handlers: {}, /* store a list of handler functions against each event */
/**
* @param {String} eventName
* @param {Function} callback
*/
on: function(eventName, callback) {
/*
When on is called, add the callback to the list of registered callback for this event type.
*/
if (this.handlers.hasOwnProperty(eventName)) {
this.handlers[eventName].push(callback);
} else {
this.handlers[eventName] = [callback];
}
},
/**
* @param {String} eventName
*/
emit: function(eventName) {
/*
Execute all of the callbacks associated with this eventEmitter and eventName.
*/
if (this.handlers.hasOwnProperty(eventName)) {
this.handlers[eventName].forEach(function(handler) {
handler();
});
}
}
};
/*
Sample usage of the EventEmitter Object
*/
var myEmitter = Object.create(EventEmitter);
myEmitter.on("my-event", function() {
console.log("my-event fired, First callback.");
});
myEmitter.on("my-event", function() {
console.log("my-event fired, Second callback.");
});
myEmitter.on("your-event", function() {
console.log("your-event fired.");
});
myEmitter.emit("your-event");
myEmitter.emit("my-event");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment