Advertisement
crutch12

Untitled

May 26th, 2020
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // use-event-bus.ts
  2. import { provide, inject } from '@vue/composition-api';
  3. import EventEmitter from 'eventemitter3';
  4.  
  5. const EventBusDefaultSymbol = Symbol('Default event bus symbol');
  6.  
  7. export function provideEventBus(eventBus: EventEmitter, eventBusSymbol = EventBusDefaultSymbol) {
  8.   provide(eventBusSymbol, eventBus);
  9.   return () => provide(eventBusSymbol, undefined);
  10. }
  11.  
  12. export function useEventBus(eventBusSymbol = EventBusDefaultSymbol) {
  13.   const eventBus = inject(eventBusSymbol);
  14.   if (!eventBus) {
  15.     throw new Error('Event bus not found');
  16.   }
  17.   return eventBus;
  18. }
  19.  
  20.  
  21. // parent.vue
  22. import { provideEventBus } from '../../composition/use-event-bus';
  23. ...
  24. setup(props, context) {
  25.     const eventBus = new EventEmitter();
  26.     const eventBusSymbol = Symbol('rsm network event bus symbol');
  27.  
  28.     provideEventBus(eventBus, eventBusSymbol);
  29.     return {
  30.         eventBus,
  31.         eventBusSymbol,
  32.     };
  33. },
  34.  
  35.  
  36. // child.vue
  37. import { useEventBus } from '../../composition/use-event-bus';
  38. ...
  39. setup(props, context) {
  40.     const eventBusSymbol = props.eventBusSymbol as symbol;
  41.     const eventBus = eventBusSymbol ? useEventBus(eventBusSymbol) : null;
  42.  
  43.     return {
  44.         eventBus,
  45.     };
  46. },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement