订阅/发布模式

订阅发布模式

在这种模式中,并不是⼀个对象调⽤另⼀个对象的⽅法,⽽是⼀个对象订阅另⼀个对象的 特定活动并在
状态改编后获得通知。订阅者因此也成为观察者,⽽被观察的对象成为发布者或者主题。当发⽣了⼀个
重要事件时候 发布者会通知(调⽤)所有订阅者并且可能经常已事件对象的形式传递消息

vue中的 emit, on源码 ⼤概也是这个样⼦ vue源码

完整的演示代码

class A {
  constructor() {
    // 存储事件
    this.callbacks = {};
  }
  $on(name, fn) {
    (this.callbacks[name] || (this.callbacks[name] = [])).push(fn);
  }
  $emit(name, arg) {
    let cbs = this.callbacks[name];
    if (cbs) {
      cbs.forEach(v => {
        v.call(this, arg);
      });
    }
  }
  $off(name) {
    this.callbacks[name] = null;
  }
}

var a = new A();

// 绑定事件
a.$on("event", function(arg) {
  console.log("事件1", arg);
});

a.$on("event2", function(arg) {
  console.log("事件2", arg);
});

// 触发事件
a.$emit("event", { name: "sh" });

// 取消事件
a.$off("event");

// 取消之后尝试触发事件
a.$emit("event", { name: "sh" });
posted @ 2020-03-18 15:49  残梦a  阅读(227)  评论(0编辑  收藏  举报