zoukankan      html  css  js  c++  java
  • 订阅/发布模式

    订阅发布模式

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

    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" });
    
  • 相关阅读:
    项目纪实一
    Quartz.net一个简要示例
    ASP.NET MVC4 WebAPI若干要点
    利用委托实现父控件与子控件之间消息传递
    js获取屏幕信息
    jsion大括号和中括号,及调用
    jquery解析jsion
    hibernate初步
    java web笔记
    mysql存储过程
  • 原文地址:https://www.cnblogs.com/sunhang32/p/12517827.html
Copyright © 2011-2022 走看看