class CustomEvent {
  constructor() {
    // {
    //   eventName: [];
    // }
    this.eventsKeeper = {};
  }

  isAssigned(name, cb) {
    const keeper = this.eventsKeeper;
    if (!cb) {
      return name in keeper;
    } else {
      return name in keeper && keeper[name].indexOf(cb) !== -1;
    }
  }

  on(name, cb) {
    const keeper = this.eventsKeeper;
    const cbs = keeper[name];
    if (this.isAssigned(name, cb)) return;
    if (!cbs) {
      keeper[name] = [cb];
    } else {
      keeper[name].push(cb);
    }
  }

  emit(name, ...rest) {
    if (this.isAssigned(name)) {
      this.eventsKeeper[name].forEach(cb => {
        cb(...rest);
      });
    } else {
      throw Error(`you may not listen [${name}] event!`);
    }
  }

  remove(name) {
    if (!name) return;
    delete this.eventsKeeper[name];
  }
}


// test
// node test.js

// const event = new CustomEvent();

// event.on("test", (first, second) => {
//   console.log(`${first} ${second}`);
//   console.log("it is ok");
// });

// event.on("test", () => {
//   console.log("it is line ok");
// });

// event.remove("test");

// event.on("line", () => {
//   console.log("it is line ok ");
// });

// event.emit("line");

// setTimeout(() => {
//   event.emit("test", "hello", "world");
// }, 2000);

版权声明:本文为looyulong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/looyulong/p/10977249.html