发布订阅模式

发布订阅模式 — 一对多的关系

image.png

场景:售楼

  1. 主题(售楼处)
  2. 缓存列表 -> 缓存监听器绑定的回调函数
  3. 当事件触发的时候 -> 状态发生变化 -> 依次执行回调函数

image.png
只监听不同的事件感兴趣,比如张三只对88感兴趣,李四对108感兴趣,当88发生变化,只有张三接受通知,当108发生变化,只有李四接受到通知
image.png

通用对象

  1. var Event = {
  2. clientList: [],
  3. listen: function(key, fn) {
  4. if(!this.clientList[key]) {
  5. this.clientList[key] = [];
  6. }
  7. this.clientList[key].push(fn);
  8. }
  9. trigger() {
  10. var key = Array.prototype.shift.call(arguments),
  11. fns = this.clientList[key];
  12. for(var i = 0; i < fns.length; i++) {
  13. fns[i].apply(this, arguments);
  14. }
  15. }
  16. }
  17. function installEvent(target, Source) {
  18. for(var i in Source){
  19. target[i] = Source[i];
  20. }
  21. return target;
  22. // return Object.assign(target, Source);
  23. }
  24. // 把Event对象的属性方法拷贝到target上
  25. var salesOffices = installEvent(salesOffices, Event);

使用ES6方式

  1. class Event {
  2. constructor() {
  3. this.clientList = [];
  4. }
  5. listen(key, fn) {
  6. if(!this.clientList[key]) {
  7. this.clientList[key] = [];
  8. }
  9. this.clientList[key].push(fn);
  10. }
  11. trigger() {
  12. var key = Array.prototype.shift.call(arguments),
  13. fns = this.clientList[key];
  14. for(var i = 0; i < fns.length; i++) {
  15. fns[i].apply(this, arguments);
  16. }
  17. }
  18. }
  19. class SalesOffices extends Event{
  20. constructor() {
  21. super();
  22. }
  23. }
  24. var salesOffices = new SalesOffices();