Hi-Bus一个新的事件总线,欢迎测试

203 阅读1分钟

自己的项目里面为了实现更快捷的事件发布和订阅,于是就自己重新开发了一个事件总线组件,用用觉得不错,于是遂打算拿出来和大家分享分享,欢迎大家测试指教。

这个事件总线是基于Typescript的装饰器开发的,所以目前只能使用Typescript才能使用,不过用起来确实很方便的哦。

这里我就先放上一下使用代码,项目连接在底部

// Import Hi-Bus, you can use any word instead 'HiBus'
import HiBus, {Bus, Publish, Subscribe} from 'hi-bus'

// First we must create a class with decorate ‘@Bus'
// decorate '@Bus’ is used to collect subscribe functions
// it will not work without '@Bus’ when you subscribe message in class

@Bus
class Test {  

  // Subscribe topic “handshake” with doctorate @Subscribe
  // You only focus the function logic
  @Subscribe("handshake")
  handshake() {
    console.log(“Handshake”);
  }

  // when you call function ‘pulbishHandshake’
  // it will publish topic ‘handshake’ automatic
  // the function must return something to trigger publish
  // if return nothing or return void, it will not trigger publish
  @Publish("handshake")
  publishHandshake() {
    return {};
  }

}

const test = new Test();

test.publishHandshake();
// console output: Handshake

Hi-Bus GitHub项目地址