码迷,mamicode.com
首页 > 其他好文 > 详细

es6 发布-订阅模式

时间:2017-09-20 19:44:10      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:cal   app   out   xtend   color   注册   订阅   als   ini   

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);
});

 

es6 发布-订阅模式

标签:cal   app   out   xtend   color   注册   订阅   als   ini   

原文地址:http://www.cnblogs.com/longor/p/7562709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!