手寫一個簡單的發布者訂閱者模式


手寫一個發布者訂閱者模式:

 // 手寫發布訂閱模式 EventEmitter
      class EventEmitter {
        constructor() {
          this.events = {};
        }
        // 實現訂閱
        on(type, callBack) {
          if (!this.events) this.events = Object.create(null);

          if (!this.events[type]) {
            this.events[type] = [callBack];
          } else {
            this.events[type].push(callBack);
          }
        }
        // 刪除訂閱
        off(type, callBack) {
          if (!this.events[type]) return;
          this.events[type] = this.events[type].filter(item => {
            return item !== callBack;
          });
        }
        // 只執行一次訂閱事件
        once(type, callBack) {
          function fn() {
            callBack();
            this.off(type, fn);
          }
          this.on(type, fn);
        }
        // 觸發事件
        emit(type, ...rest) {
          this.events[type] &&
            this.events[type].forEach(fn => fn.apply(this, rest));
        }
      }
// 使用如下
      const event = new EventEmitter();

      const handle = (...rest) => {
        console.log(rest);
      };

      event.on("click", handle);

      event.emit("click", 1, 2, 3, 4);

      event.off("click", handle);

      event.emit("click", 1, 2);

      event.once("dbClick", () => {
        console.log(123456);
      });
      event.emit("dbClick");
      event.emit("dbClick");

Ok


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM