Publisher

by secretgspot

JavaScript

(function(window, undefined) {
    var Publisher = function() {
        var attachments = [],
            events = [];
        
        this.Event = {};
        this.Module = {};        
        
    };
    
        Publisher.prototype.addModule = function(name, object) {
            this.Module[name] = object;
            return this;
        };
        
        Publisher.prototype.addEventName = function(event) {
            this.Event[event] = [];            
            return this;            
        };
        
        Publisher.prototype.subscribe = function(event, reaction) {
            event.push(reaction);
            return this;
        };
        
        Publisher.prototype.publish = function() {
            var i,
                event = this.Event[arguments[0]],
                length = event.length;
            
            if (arguments.length > 1) {
                arguments = Array.prototype.slice.call(arguments, 1);
            } else {
                // preserve functionality of method call w no arguments
                arguments = undefined;
            }
            
            for (i = 0; i < length; ++i) {
                event[i].apply(this, arguments);    
            }
            
            return this;
        };    
    
    window.Publisher = new Publisher();
}(window));

var talk = { "sayHi": function(name) { console.log("hi," + name + "!"); 
                                       this.Module.talk.sayBye();
                                       return this; },
             "sayBye": function() { console.log("bye"); return this; }};

Publisher.addModule("talk", talk).addEventName("greet")
    .subscribe(Publisher.Event.greet, Publisher.Module.talk.sayHi)
    .publish("greet", "Mary", "Bob");