function init() {
// I'm creating a stand alone object, but you could create a new class which extends it using prototypical inheritence.
var ee = new EventEmitter();
// Add some listeners.
ee.addListener('create-user', sendCreateRequest);
ee.addListener('request-complete', displayResponse);
// These are the callback functions.
function sendCreateRequest(name) {
// Somewhere else in the code handles the request...
sendRequest('create', arguments, function(success, response) {
// When the request is complete, trigger the event and pass it the response.
ee.emitEvent('request-complete', arguments);
// emitEvent takes an array of arguments as its second parameter.
// You can also use emit if you prefer the old style API:
// ee.emit('request-complete', success, response);
// The new array method is a lot more versatile.
});
}
function displayResponse(success, response) {
// Show a popup based on the arguments...
if (success) {
console.log('Yay!');
}
else {
console.log('Boo!');
}
}
function sendRequest(type, data, callback) {
// Do request magic here...
callback(true, {name: data[0]});
}
// Kick everything off by emitting a create-user event.
ee.emitEvent('create-user', ['Oliver Caldwell']);
}
/*!
* EventEmitter v4.1.0 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/
!function(r){"use strict";function t(){}function n(n,e){if(i)return e.indexOf(n);for(var t=e.length;t--;)if(e[t]===n)return t;return-1}var e=t.prototype,i=Array.prototype.indexOf?!0:!1;e._getEvents=function(){return this._events||(this._events={})},e.getListeners=function(n){var r,e,t=this._getEvents();if("object"==typeof n){r={};for(e in t)t.hasOwnProperty(e)&&n.test(e)&&(r[e]=t[e])}else r=t[n]||(t[n]=[]);return...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.