前端订阅-发布模式

前端订阅-发布模式

var Fanctories = {};
Fanctories.clientList = [];

Fanctories.subscribe = function (theme,person) {
    if(person.theme.indexOf(theme)<0){
        person.theme.push(theme);
    }
    if(!this.clientList[theme]){
        this.clientList[theme]=[];
    }
    this.clientList[theme].push(person);
};

Fanctories.publish = function () {    //发布消息
    var theme = Array.prototype.shift.call(arguments),
        persons= this.clientList[theme];
    if(!persons || persons.length===0){
        return false;
    }
    for(var i = 0, person;i<persons.length;){
        person = persons[i++];
        console.log(arguments);
        person.news.push(arguments[0]);
        person.fn.apply(this, arguments); //apply方法能劫持另外一个对象的方法,继承另外一个对象的属性
    }
}

function Person(name){
    this.name =name;
    this.theme =[];
    this.news=[];
    this.fn=function(arguments){console.log(arguments);}
}

var XG = new Person("小刚");
var XH = new Person("小红");
var XQ = new Person("小倩");

Fanctories.subscribe("体育频道",XG);
Fanctories.subscribe("少儿频道",XG);
Fanctories.subscribe("少儿频道",XH);

Fanctories.publish("体育频道",{title:'足球',path:'世界杯'});
Fanctories.publish("体育频道",{title:'奥运会',path:'乒乓球'});
Fanctories.publish("少儿频道",{title:'蓝猫淘气',path:'恐龙时代篇'});
Fanctories.publish("外语频道",{title:'荒野求生',path:'河中捉鳖'});

console.log(`${XG.name} 订阅的主题:[${XG.theme}],内容:`,XG.news);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值