美文网首页
编写一个自定义事件类,包含on/off/emit/once方法

编写一个自定义事件类,包含on/off/emit/once方法

作者: Yong_bcf4 | 来源:发表于2020-12-15 17:00 被阅读0次
function Event() {
this._events = {}
}

Event.prototype.on = function(type, fn) {
if(!this._events[type]) {
  this._events[type] = []
}
this._events[type].push(fn)
}

Event.prototype.off = function(type, fn) {
if(!this._events[type]) {
  return
}
if(!fn) {
  this._events[type] = undefined
  return
}
var index = this._events[type].indexOf(fn)
this._events[type].splice(index, 1)
}

Event.prototype.emit = function(type) {
if(!this._events[type]){
  return
}
thi._events[type].forEach(fn => fn())
}

Event.prototype.once = function(type, fn) {
var _ = this;
var _fn = () => {
  fn.apply(_, arguments){
    this.off(type)
  }
}
this.on(type, _fn)
}

相关文章

  • VUE $on/$emit实现

    这个文章介绍如何实现 vue的$on $emit $once $off 。 不懂$on $emit $once $...

  • socket 实例-客户端

    简介 1 .Socket是与服务器交互的基础类.2 .继承的方法.emit,on,once,off3 .还有一些属...

  • vue组件如何通信

    父传子:props; 子传父:this.$emit 自定义事件:event.emit触发 event.$off...

  • 笔试题

    实现一个自定义事件Event对象的接口,继承该对象都拥有on 、off、emit三个方法 请实现瀑布流布局,如下图...

  • vue中$refs, $emit, $on, $once, $o

    $once监听一个自定义事件。 $off移除自定义事件监听器。 只能监听自定义事件 推荐的清除定时器 直接在需要定...

  • 深度解析node的EventEmitter

    在使用EventEmitter的时候我们常用的方法主要有on、emit、once、off, 下面我们简单实现一下这...

  • 每日一条JS精华片段:创建一个发布/订阅 事件器

    创建一个发布/订阅事件器,拥有emit,on和off方法。 Javascript方法 示例 请关注我,每天获得一条...

  • vue实现一个eventBus

    eventBus应该有些听过,其实就是一个事件发布订阅的功能。vue提供了实例方法事件,就是once、emit。 ...

  • Observer 事件机制封装

    目标:封装一个对象,使其拥有 $on , $emit 和 $off 方法,进行事件的订阅、抛发和移除。 实现过程如下:

  • EventEmitter模块实验

    阿里面试题为例 完成 EventEmitter 模块,它是一个类,它的实例具有以下几个方法:on、emit、off...

网友评论

      本文标题:编写一个自定义事件类,包含on/off/emit/once方法

      本文链接:https://www.haomeiwen.com/subject/rdcogktx.html