EventEmitter (v4.1.0) - Simple

A simple example of using EventEmitter.

by Oliver Caldwell

JavaScript

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...