enhance-eventbus
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

enhance-eventbus

NPM Download NPM Version NPM License PRs Welcome typescript package size

介绍

eventBus 是一个典型的发布订阅模式的实践,而这个包的基础功能就是发布订阅。

eventBusnode.js 中本就自带,所以为什么需要写这个包呢?

其实从包名 enhance-eventbus 中也可以看出来,这是一个增强 (其实是不会起名字) 的 eventBus

它比普通的 eventBus 多了可以在浏览器跨 tab (有同源限制)。

它的 api 跟普通的 eventBus 是一样的使用方式的,极其简单, 相信使用过 vue 里面 eventBusnew 一个 vue 实例作为eventBus)的小伙伴们, 都知道怎么使用~

example

example

StorageEventBus

这里实现原理是利用了 storage 去监听的,所以这里在相同一个 window tab 页面是无法触发事件的,需要开启别的 tab 才能通信。

// yarn add enhance-eventbus or npm i -S enhance-eventbus
 
const eventBus = new tabeventbus.StorageEventBus({
  isDev: () => true
})
 
eventBus.on('someEvent', (data) => {
 
  console.log(data)
})
 
eventBus.emit('someEvent', {msg: 'hello world'})

use in your vue project

// in the main.js
import enhanceEventbus from "enhance-eventbus"
import Vue from "vue"
 
Vue.use(enhanceEventbus, {
  type: "storage",
  globalKey: "$eventBus" // 这里配置的是 vue.prototype 挂载的属性名叫什么
})
 
// and then you can use it by the gloalKey that your define
 
new Vue({
 
  mounted() {
    this.$eventBus.on('someEvent', (data) => {
      // ...to do sth
    })
 
    this.$eventBus.emit('someEvent', data)
  }
})

感谢以下项目(排名不分先后)

Package Sidebar

Install

npm i enhance-eventbus

Weekly Downloads

63

Version

1.0.6

License

MIT

Unpacked Size

59.5 kB

Total Files

19

Last publish

Collaborators

  • cjfff