JSFiddle - React, Tailwind, and code Playground

by Thomas Upton

HTML

<div id="content"></div>

JavaScript

var subscriber = (function() {
    
    var _listeners = {};
        
    return {
        // Listen to a channel and call a callback when that channel fires
        listen: function(channel, cb) {
            // Add the callback to the list of listeners on the given channel
            _listeners[channel] = _listeners[channel] || [];
            _listeners[channel].push(cb);
            
            return {
                // Return an object that can be used to remove the callback from the channel
                unlisten: function() {
                    // Remove the callback from the list of listeners on that channel
                    _listeners[channel].splice(_listeners[channel].indexOf(cb), 1);
                }
            }
        },
        
        // Manually fire events on a given channel.
        publish: function(channel) {
            _listeners[channel] = _listeners[channel] || [];
            _listeners[channel].forEach(function(cb) {
                cb();
            });
        }
    };
})();

var log = function(msg) {
    document.getElementById('content').innerHTML += msg + '<br />';
};

var h = subscriber.listen('update', function() {
    log("The update event was fired!");
});

var i = subscriber.listen('update', function() {
    log("The update event was fired to another listener.");
});

subscriber.publish('update'); // > "The update event was fired!"

h.unlisten();

subscriber.publish('update'); // > <no output for `h`>