JSFiddle - React, Tailwind, and code Playground

by Sean Coker

JavaScript

var EventSubscriber = function(){
    this.listeners = {};
};
EventSubscriber.prototype.listeners = null;
EventSubscriber.prototype.isSubscribed = function(type){
    return this.listeners[type] != null;
};
EventSubscriber.prototype.subscribe = function(type, callback){
    if(!this.isSubscribed(type)) {
        this.listeners[type] = [];
    };
    this.listeners[type].push(callback);
};
EventSubscriber.prototype.unsubscribe = function(type, callback){
    if(!this.isSubscribed(type)) {
        return;
    };
    var stack = this.listeners[type];
    for(var i = 0, l = stack.length; i < l; i++){
        if(stack[i] === callback){
            stack.splice(i, 1);
            return this.unsubscribe(type, callback);
        };
    };
};
EventSubscriber.prototype.broadcast = function(type, params){
    if(!this.isSubscribed(type)) {
        return;
    };
    var stack = this.listeners[type];
    for(var i = 0, l = stack.length; i < l; i++) {
        stack[i].apply(this, params);
    };
};

var e = new EventSubscriber();
e.subscribe('moved', function(){
    alert('reacting to event:moved');
});
e.broadcast('moved');