实现一个Event类

包含的功能:

  • 绑定事件 on(eventName, func)监听eventName事件,事件触发的时候指向func函数
  • 解绑事件 off(eventName, func) 停止监听某个事件
  • 派发事件 emit(eventName, args1, args2...) 触发eventName事件,并且将args1, args2...等参数传递给事件处理函数
    需要一个_cache的对象来记录我们绑定的事件,而事件触发的时候我们需要从_cache中读取出来事件回调,依次执行他们
class Event {
  constructor() {
    this._cache = {};
  }
  on(type, callback) {
    let fns;
    if (this._cache[type]) {
      fns = this._cache[type];
    } else {
      fns = this._cache[key] = [];
    }
    if (!fns.includes(callback)) {
      fns.push(callback);
    }
    return this;
  }
  trigger(type, ...args) {
    const fns = this._cache[type];
    if (Array.isArray(fns)) {
      fns.forEach(fn => fn(...args));
    }
    return this;
  }
  off(type, callback) {
    const fns = this._cache[type];
    if (Array.isArray(fns)) {
      if (callback) {
        const index = fns.indexOf(callback);
        if (index !== -1) {
          fns.splice(index, 1);
        }
      } else {
        // 没有提供具体的回调函数,则全部取消
        fns.length = 0;
      }
    }
    return this;
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 函数 1.1 函数的 3 种定义方法 1.1.1 函数声明 //ES5 functiongetSum(){}...
    Mrssssss阅读 395评论 0 0
  • 1.数据类型 1.1概念篇 7种原始数据类型 引用类型 null是对象吗?为什么? 结论: null不是对象 解释...
    859z阅读 415评论 0 0
  • Ember Namespace Emberjs API:http://emberjs.com/api/定义于:pa...
    vincentx阅读 868评论 0 0
  • title: 小程序教程之wepy 参考文档 中文文档:https://tencent.github.io/wep...
    采香行处蹙连钱阅读 12,052评论 8 24
  • 官方文档 快速入门 安装 生成工程 进入工程目录 实时编译项目 wepy build --watch 注意事项: ...
    ROBIN2015阅读 1,118评论 0 1