js事件订阅、发布

    var eventCenter={
        sub:function(mesName,mesCallback){
            this.argus=this.argus||{};
            this.argus[mesName]=this.argus[mesName]||[];
            this.argus[mesName].push(mesCallback)
        },
        pub:function(){
            var args=Array.prototype.slice.call(arguments,0);
            var mesName=args.shift();
            if(!this.argus || !this.argus[mesName]){
                return this;
            }
            for(var i=0;i<this.argus[mesName].length;i++){
                this.argus[mesName][i].apply(this,args)
            }
        }
    }

    eventCenter.sub('a',function(){
        console.log(2)
    })

    eventCenter.pub('a')

你可能感兴趣的:(js)