美文网首页
js自定义事件

js自定义事件

作者: Nic_ofh | 来源:发表于2017-08-04 10:39 被阅读0次
class Event {

  // 监听函数
  static on(eventName, callback) {
    if (!eventName) {
      return
    }

    if (!this.handles) {
      Object.defineProperty(this, "handles", {
        value: {},    // 默认值是{}
        enumerable: false, // 不可枚举
        configurable: true, // 可以delete删除
        writable: true  // 可以修改
      })
    }

    // 如果对象中没有这个名字,就创建一个数组,之后把名字和方法存在来
    if (!this.handles[eventName]) {
      this.handles[eventName] = []
    }
    // 把对应方法push到数组里
    this.handles[eventName].push(callback)
  }

  // 触发函数
  static emit(eventName) {
    let nameAry = this.handles[eventName]
    // 处理对象里存在这个名字的数组,就把数组的方法执行了
    if (nameAry instanceof Array) {
      for (let i = 0; i < nameAry.length; i++) {
        nameAry[i]()
      }
    }
  }

  // 解绑函数
  static off(eventName) {
    let nameAry = this.handles[eventName]
    if (nameAry instanceof Array) {
      this.handles[eventName] = null
    }
  }
}

Event.on('oufuhua', function () {
  console.log('哈哈哈')
})

Event.on('oufuhua', function () {
  console.log('我叫oufuhua')
})

// Event.off('oufuhua')

 Event.emit('oufuhua')

相关文章

  • 自定义事件js

    title: 自定义事件date: 2017-06-06 15:36:04tags: 自定义事件 js的自定义事件...

  • jQuery例子记录(持续更新)

    目录: 1.自定义事件2.操作DOM(与JS原生对比) 1.自定义事件 绑定自定义事件: 事件名称refresh....

  • JS中的事件

    JS中的事件 一:自定义事件 1.使用Event自定义事件 使用Event接口,可以自定义事件。但是该接口无法在事...

  • mitt

    安装 js 引入: 发送mybus.emit('自定义事件名称','数据');接收mybus.on('自定义事件名...

  • Markdown

    touch.js学习 准备工作 引用 touch.js是百度开源的一套支持原生js事件和自定义事件的js库...

  • MarkDown学习

    touch.js学习 准备工作 touch.js是百度开源的一套支持原生js事件和自定义事件的js库js中包含很多...

  • MARKDOWN学习?

    touch.js学习 准备工作 touch.js是百度开源的一套支持原生js事件和自定义事件的js库js中包含很多...

  • touch.js

    touch.js学习 touch.js是百度开源的一套支持原生js事件和自定义事件的js库js中包含很多这种库 封...

  • IFE2017,动态数据绑定(二)学习笔记

    自定义事件 我们知道JS里绑定事件有addEventListener()这个方法。在JS中我们可以这样创建一个自定...

  • MarkDown学习

    touch.js学习 1.准备工作 touch.js是百度开源的一套支持原生js事件和自定义事件的js库js中包含...

网友评论

      本文标题:js自定义事件

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