【JS基础】订阅发布模式

2017-11-03  本文已影响0人  六毫笙

最 新:https://www.zybuluo.com/c-Ku/note/934090

代码示例

// Based on ES5
var login = {};

login.eventList = {};

// 将函数推入数组中保存,待用
login.listen = function(key, fn) {

    if (!this.eventList[key]) {
    
        this.eventList[key] = [];
        
    }
    
    this.eventList[key].push(fn);
    
}
login.trigger = function(key) {

    var fns = this.eventList[key];
    
    if (!fns || fns.length === 0) {
    
        return false;
        
    }
    
    for (var i=0; i<fns.length;i++) {
    
        fns[i]();
        
    }
}

// 订阅
login.listen('loginSuccess', function() {

    console.log('显示用户头像');
    
})

login.listen('loginSuccess', function() {

    console.log('显示消息列表');
    
})

// 发布
login.trigger('loginSuccess');
上一篇 下一篇

猜你喜欢

热点阅读