发布订阅模式

2021-01-12  本文已影响0人  bestCindy
let shoeObj = {};//定义发布者
shoeObj.list = [];//缓存列表 存放订阅者的回调函数

//增加订阅者
shoeObj.listen = function(fn) {
    shoeObj.list.push(fn);//订阅消息添加到缓存列表
}

//发布消息
shoeObj.trigger = function() {
    for (let i = 0; i < this.list.length; i++) {
        this.list[i].apply(this, arguments);
    }
}

//订阅消息
shoeObj.listen(function(color, size) {
    console.log("the color is: " + color);
    console.log("the size is: " + size);
})

shoeObj.listen(function(color, size) {
    console.log("print the color again: " + color);
    console.log("print the size again: " + size);
})

shoeObj.trigger("red", 37);
shoeObj.trigger("black", 38);
上一篇 下一篇

猜你喜欢

热点阅读