js custom-event

---

title: js custom-event

date: 2018-09-08 20:41:49

tags:

---

#### 类似于 jq的.on('click',fn) 的自定义事件

  ```js

  class Emitter  {

      constructor(_listeners) {

          this._listeners = {}; //一个全局的对象

      }

      // Method

      subscribe(type,callback) { // 注册事件

          if (typeof this._listeners[type] === "undefined") {

              this._listeners[type] = [];

          }

          if (typeof callback === "function") {

              this._listeners[type].push(callback); //把事件函数存进去

          }

          return this;

      }

      emit(type) { // 触发事件

          var args = Array.prototype.slice.call(arguments, 0)

          var event = args.shift()

          var list, events

          if ( !(events = this._listeners) ) return

          if ( !(list = this._listeners[event]) ) return

          for (var i=0; i<list.length; i++) { // 把参数传进去

              list[i].apply(this, args)

          }

          return this

      }

      release(type, fn) { // 释放

          if (typeof type === "string") {

              this._listeners[type].splice(fn, 1);

          }

          return this;

      }

  }

  const emitter = new Emitter(); //初始化 emitter

  const array = [];

  const sub1 = emitter.subscribe('click',  (...args)=> console.log(args)); //注册

  array.push({sub1:0})

  const sub2 = emitter.subscribe('click',  (...args)=> console.log(args));

  array.push({sub1:1})

  emitter.release('click', array.sub1) // 释放

  emitter.emit('click',1,2) // 唤起



  ```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容