发布/订阅(Pub/Sub)模式的简单实现

var PubSub = {
        subscribe: function (ev, cb) {
            var calls = this._cbs || (this._cbs = {});
            (this._cbs[ev] || (this._cbs[ev] = [])).push(cb);
            return this;
        },
        publish: function () {
            var args = [].slice.call(arguments, 0);
            var ev = args.shift();

            var list, calls, i, l;
            if (!(calls = this._cbs)) return this;
            if (!(list = this._cbs[ev])) return this;

            for (i = 0, l = list.length; i < l; i++) {
                list[i].apply(this, args);
            }
            return this;
        }
    };

    PubSub.subscribe('hello', function (data) {
        console.log(data);
    });
    
    PubSub.publish('hello', '你好啊,我是参数。');

 

基于jquery的发布/订阅(Pub/Sub)实现:

(function () {
        var o = $({});
        
        $.subscribe = function() {
            o.bind.apply(o, arguments);
        };
        
        $.unsubscribe = function() {
            o.unbind.apply(o, arguments);
        };
        
        $.publish = function() {
            o.trigger.apply(o, arguments);
        };
    })(jQuery);

 

你可能感兴趣的:(js,开发)