美文网首页
发布订阅模式

发布订阅模式

作者: bestCindy | 来源:发表于2021-01-12 10:50 被阅读0次
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);

相关文章

网友评论

      本文标题:发布订阅模式

      本文链接:https://www.haomeiwen.com/subject/afbjaktx.html