一个订阅发布者模式

常见的订阅发布者模式的编写

(function(window) {
    function Subscribe() {
        this.events = {};
    };
    Subscribe.prototype.subscribe = function(eventName, fn) {
        (!this.events[eventName]) && (this.events[eventName] = []);
        this.events[eventName].push(fn);
        return this;
    };
    Subscribe.prototype.unsubscribe = function(eventName, fn) {
        var events = this.events;
        if (eventName in events) {
            delete events[eventName];
        }
        return this;
    };
    Subscribe.prototype.publish = function(eventName) {
        var args = [].slice.call(arguments, 1),
                events = this.events;
        if (eventName in events) {
            for (var i = 0, len = events[eventName].length; i < len; i++) {
                events[eventName][i].apply(this, args);
            }
        }
        return this;
    };

    window.Subscribe = new Subscribe();
})(window);

你可能感兴趣的:(Javascript)