发布订阅模式 — 一对多的关系
场景:售楼
- 主题(售楼处)
- 缓存列表 -> 缓存监听器绑定的回调函数
- 当事件触发的时候 -> 状态发生变化 -> 依次执行回调函数

只监听不同的事件感兴趣,比如张三只对88感兴趣,李四对108感兴趣,当88发生变化,只有张三接受通知,当108发生变化,只有李四接受到通知
通用对象
var Event = {clientList: [],listen: function(key, fn) {if(!this.clientList[key]) {this.clientList[key] = [];}this.clientList[key].push(fn);}trigger() {var key = Array.prototype.shift.call(arguments),fns = this.clientList[key];for(var i = 0; i < fns.length; i++) {fns[i].apply(this, arguments);}}}function installEvent(target, Source) {for(var i in Source){target[i] = Source[i];}return target;// return Object.assign(target, Source);}// 把Event对象的属性方法拷贝到target上var salesOffices = installEvent(salesOffices, Event);
使用ES6方式
class Event {constructor() {this.clientList = [];}listen(key, fn) {if(!this.clientList[key]) {this.clientList[key] = [];}this.clientList[key].push(fn);}trigger() {var key = Array.prototype.shift.call(arguments),fns = this.clientList[key];for(var i = 0; i < fns.length; i++) {fns[i].apply(this, arguments);}}}class SalesOffices extends Event{constructor() {super();}}var salesOffices = new SalesOffices();
