Last active
February 13, 2017 19:44
-
-
Save amalantony/1901c99f9967277534f8e53765451dd2 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
/* | |
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