发布-订阅模式
2018-04-18 本文已影响0人
小丸子啦啦啦呀
红绿灯
class Light{
constructor() {
this.drivers = [];
}
// 只用缓存订阅者的接收方法,而不需要他的个人信息
regist(fn){
this.drivers.push(fn);
}
sendMsg() {
this.drivers.forEach(fn => {
// driver.recieveMsg(msg);
// fn.apply(this, msg);
fn.apply(this, arguments);
});
}
}
class Driver{
constructor(name) {
this.name = name;
}
recieveMsg(msg) {
// 如果用apply的话,订阅者如果知道发布者保存所有订阅者的变量名drivers,那么他就可以访问到别的订阅者的订阅函函数
console.log(' recieve ' + this.drivers);
}
}
const light = new Light();
const driver1 = new Driver('driver1');
const driver2 = new Driver('driver2');
const driver3 = new Driver('driver3');
light.regist(driver1.recieveMsg);
light.regist(driver2.recieveMsg);
light.regist(driver3.recieveMsg);
light.sendMsg('red!');
只订阅自己想订阅的内容
class Light{
constructor() {
this.drivers = [];
// {
// red: [fn1. fn2, fn3],
// ...
// }
}
regist(key, fn){
// 订阅新关键字
if (!this.drivers[key]){
this.drivers[key] = [];
}
this.drivers[key].push(fn);
}
sendMsg(key) {
if(!this.drivers[key])return false;
this.drivers[key].forEach(fn => {
fn.apply(this, arguments);
});
}
}
class Driver{
constructor(name) {
this.name = name;
}
recieveMsg(msg) {
console.log(' recieve ' + msg);
}
}
const light = new Light();
const driver1 = new Driver('driver1');
const driver2 = new Driver('driver2');
const driver3 = new Driver('driver3');
light.regist('red', driver1.recieveMsg);
light.regist('green', driver2.recieveMsg);
light.regist('yellow', driver3.recieveMsg);
console.log(light);
light.sendMsg('red');