es6 发布-订阅模式

class Event {
    constructor() {
        //保存事件列表
        this.eventList = [];
    }
    on(key,fn){
        if ( !this.eventList[ key ] ){ 
            this.eventList[ key ] = []; 
        } 
        this.eventList[ key ].push( fn );
    }
    trigger(){
        var key = Array.prototype.shift.call( arguments ),
            fns = this.eventList[ key ]; 
        if ( !fns || fns.length === 0 ){
            return false; 
        } 
        for( var i = 0, fn; fn = fns[ i++ ]; ){ 
            fn.apply( this, arguments );
        } 
    }
}

//继承
class Test extends Event {
    constructor() {
        super();
        this.init();
    }
    init(){
        window.setTimeout(()=>{
            this.trigger('test','word:123','key:test');
        },3000);
    }
}

let t = new Test();

t.on('test',(word,key)=>{
    alert(word);
    alert(key);
});

//重复注册
t.on('test',(word,key)=>{
    alert(key);
    alert(word);
});

 

posted @ 2017-09-20 17:31  longorYang  阅读(352)  评论(0编辑  收藏  举报