前端订阅-发布模式
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);