家政小程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

eventBus.js 956B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. class EventBus {
  2. constructor() {
  3. this.events = {};
  4. }
  5. /**
  6. * @param {any} type 事件名称
  7. * @param {any} handler 事件处理器 暂时支持一个事件只有一个处理器
  8. * @param {any} isKeep 是否保持常驻不被消费
  9. * @returns
  10. */
  11. on(type, handler, isKeep) {
  12. this.events[type] = handler;
  13. if (isKeep) this.events[type].isKeep = true;
  14. return this;
  15. }
  16. //取消订阅事件
  17. off(type) {
  18. if (!type) {
  19. return this;
  20. }
  21. delete this.events[type];
  22. return this;
  23. }
  24. //触发事件
  25. emit(type, data, callback) {
  26. const fn = this.events[type];
  27. if (fn) {
  28. fn.call(this, data, callback);
  29. if (!this.events[type].isKeep) {
  30. this.events[type] = null;
  31. }
  32. }
  33. return this;
  34. }
  35. }
  36. const eventBus = new EventBus();
  37. export default eventBus;