1
0

eventHub.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. class EventHub {
  2. private cache: { [key: string]: Array<(data: any) => void> } = {};
  3. on(eventName: string, fn: (data: any) => void) {
  4. this.cache[eventName] = this.cache[eventName] || [];
  5. this.cache[eventName].push(fn);
  6. }
  7. once(eventName: string, fn: (data: any) => void) {
  8. const decor = (...args: any[]) => {
  9. fn && fn.apply(this, args);
  10. this.off(eventName, decor);
  11. };
  12. this.on(eventName, decor);
  13. return this;
  14. }
  15. emit(eventName: string, data?: any) {
  16. if (this.cache[eventName] === undefined) return;
  17. console.log('======================');
  18. console.log(this.cache, eventName);
  19. console.log('======================');
  20. this.cache[eventName].forEach((fn) => fn(data));
  21. }
  22. off(eventName: string, fn: (data: any) => void) {
  23. if (this.cache[eventName] === undefined || this.cache[eventName].length === 0) return;
  24. const i = this.cache[eventName].indexOf(fn);
  25. if (i === -1) return;
  26. this.cache[eventName].splice(i, 1);
  27. }
  28. clear() {
  29. this.cache = {};
  30. }
  31. }
  32. export default EventHub;