首页 > 编程语言 > 详细

Javascript中自定义事件

时间:2019-06-05 10:03:58      阅读:82      评论:0      收藏:0      [点我收藏+]
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);

Javascript中自定义事件

原文:https://www.cnblogs.com/looyulong/p/10977249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!