1.1.3 • Published 2 years ago
@konghayao/event-hub v1.1.3
EventHub 事件管理中心
EventHub 是一个基于 Promise 的事件管理中心,提供可观测的,具有返回的事件触发机制。
经过 Jest 单元测试,覆盖率为 100% 代码高度健全可用
example 示范
npm i @konghayao/event-hub
// using ES6 modules
import EventHub from '@konghayao/event-hub';
// using CommonJS modules
var EventHub = require('@konghayao/event-hub');
const hub = new EventHub(
// 事件模板
{
created() {
return 'created';
},
mounted() {
// this 指向 你设置的 this
return this;
},
beforeDestroy: [
() => {
this.emit('destroyed');
},
() => {
console.log('beforeDestroy');
},
],
destroyed: [
() => {
throw new Error('错误');
},
// 错误不会妨碍后面的函数执行
() => {
console.log('destroyed 后面的函数被触发啦');
},
],
},
success, // EventHub 的 第二个参数是所有函数的 this 指向
);
// 事件绑定
const handle = () => {};
hub.on('eventName2', handle);
hub.on({
eventName(...params) {
console.log('this 指向', this);
console.log('参数接收', params);
},
eventName2: [() => {}],
});
// 事件删除
hub.off('eventName2', handle);
hub.off('*'); // 删除全部事件
// 事件触发
hub.emit('eventName');
hub.emit('eventName', '12', '23232'); // 可以传入参数
const result = await hub.emit('eventName', '12', '23232'); // 等待完成并返回每个函数的数据
console.log(result);
License
MIT License