eventing-bus详解

事件总线 eventing-bus

安装

1.Node.js
npm install --save eventing-bus
2.Webpack:
yarn add eventing-bus
3.NPM
npm install --save eventing-bus

订阅事件

import EventBus from 'eventing-bus'

const callback = (name) => { console.log(`Hello, ${name}!`) };

EventBus.on("exampleEventName", callback);

发布事件

import EventBus from 'eventing-bus';

EventBus.publish("exampleEventName", "Watson");
/* After registering the subscription and publishing an event you should see
   "Hello, Watson!" printed in your console. */

多个事件总线

默认情况下,您只有一个单例事件总线实例,其中包含应用程序所有部分的订阅。但是在创建自己的私有实例的过程中没有任何阻碍(例如,对于复杂应用程序的每个逻辑上不同的部分)

import EventStream from 'eventing-bus/lib/event_stream';

/* You can use EventStream both as a constructor and as a factory function. */
const privateBus = EventStream();
const newPrivateBus = new EventStream();

这些流通过创建不会分享任何订阅,也不事件

注销事件处理程序

如果您需要注销注册(一种典型的情况是在清理UI库之后进行的注册),则可以通过以下两种方式进行:

传回的通话价值 #on
注册事件处理程序后,返回提示将是注销特定处理程序的函数

import EventBus from 'eventing-bus';

const subscription = EventBus.on('event', () => { console.log('test') })

EventBus.publish('event') // Console: 'test'

// This will unregister this (and only this) subscription.
subscription();

EventBus.publish('event') // No output in console

用 #unregisterCallback
如果您无法轻松获取返回的值#on,则可以致电#unregisterCallback。另一个好处是该功能不需要知道事件名称。通过这种方式,您可以取消注册suck回调的每一次用法

import EventBus from 'eventing-bus';

const callback = () => { console.log('test') }

EventBus.on('eventA', callback)
EventBus.on('eventB', callback)

EventBus.publish('eventA') // Console: 'test'
EventBus.publish('eventB') // Console: 'test'

EventBus.unregisterCallback(callback)

EventBus.publish('eventA') // No output in console
EventBus.publish('eventB') // No output in console

批量注销订阅

由于默认情况下EventBus是总线的单例实例,因此有时可能需要注销所有订阅(最值得注意的是-在测试过程中)。可以通过调用以下方法来完成:

#unregisterAllCallbacks
删除所有事件处理程序。

import EventBus from 'eventing-bus';

EventBus.unregisterAllCallbacks();

#unregisterCallbacksForEvent
删除特定事件的所有事件处理程序

import EventBus from 'eventing-bus';

EventBus.on('exampleEvent', () => { console.log("EXAMPLE") });
EventBus.publish("exampleEvent"); // Logs `EXAMPLE`

EventBus.unregisterCallbacksForEvent('exampleEvent');

EventBus.publish("exampleEvent"); // Empty output

详细参考地址:参考文档

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值