moke's blog

vuePress-theme-reco moke    2017 - 2020
moke's blog

Choose mode

  • dark
  • auto
  • light
分类
  • 算法
  • 博客
  • HTTP
  • 数据结构
  • 前端
  • 文档
  • JS 基础
  • Node
标签
博客
前端
  • 知识体系
  • 前端资料
  • JavaScript 专题
  • JavaScript 基础
  • JavaScript 进阶
算法
  • 算法专题
  • 数据结构
TimeLine
GitHub (opens new window)
author-avatar

moke

56

Article

17

Tag

分类
  • 算法
  • 博客
  • HTTP
  • 数据结构
  • 前端
  • 文档
  • JS 基础
  • Node
标签
博客
前端
  • 知识体系
  • 前端资料
  • JavaScript 专题
  • JavaScript 基础
  • JavaScript 进阶
算法
  • 算法专题
  • 数据结构
TimeLine
GitHub (opens new window)
  • JavaScript 专题
  • 手动实现 call、apply、bind
  • 手动实现 JSONP
  • 手动实现 Promise
  • EventEmitter
  • 防抖与节流
  • 深浅拷贝
  • Instanceof
  • New
  • 继承相关
  • 前端路由
  • Curry
  • 工具函数

EventEmitter

vuePress-theme-reco moke    2017 - 2020

EventEmitter

moke 2019-04-12 23:41:17 JavaScript

讲解: https://juejin.im/post/5c199c0ae51d452f6028a072 (opens new window)

幕布:https://mubu.com/doc/2Be2P9oKmM (opens new window)

/**
 *
 * @export
 * @class EventEmitter
 */
export default class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  on(type, handler) {
    this._events[type] = this._events[type] || []
    this._events[type].push(handler)
  }

  off(type, handler) {
    if (this._events[type]) {
      const index = this._events[type].indexOf(handler)
      if (~index) {
        this._events[type].splice(index, 1)
      }
    }
  }

  once(type, handler) {
    let fired = false
    function magic(...args) {
      this.off(type, magic)
      if (!fired) {
        fired = true
        handler.apply(this, args)
      }
    }
    this.on(type, magic)
  }

  emit(type, ...args) {
    const payload = args
    const array = this._events[type] || []
    array.forEach(handler => {
      handler.apply(this, payload)
    })
  }
}
在 GitHub 上编辑此页 (opens new window)
最后更新时间: 12/10/2019, 2:00:35 PM