1. 程式人生 > >Javascript中自定義事件

Javascript中自定義事件

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);