Event.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export default class Event {
  2. _eventMap = new Map<string, Array<(...arg: any) => void>>();
  3. on(event: string, callback: (...arg: any) => void) {
  4. if (event && typeof callback === 'function') {
  5. this._eventMap.has(event) || this._eventMap.set(event, []);
  6. this._eventMap.get(event).push(callback);
  7. }
  8. return this;
  9. }
  10. once(event: string, callback: (...arg: any) => void) {
  11. if (event && typeof callback === 'function') {
  12. const fn = (...args: any) => {
  13. callback(...args);
  14. this.off(event, fn);
  15. };
  16. this.on(event, fn);
  17. }
  18. }
  19. off(event: string, callback: null | (() => void)) {
  20. if (event) {
  21. if (typeof callback === 'function') {
  22. const callbacks = this._eventMap.get(event);
  23. if (Array.isArray(callbacks) && callbacks.length) {
  24. let index = -1;
  25. // eslint-disable-next-line max-depth
  26. while ((index = callbacks.findIndex(cb => cb === callback)) > -1) {
  27. callbacks.splice(index, 1);
  28. }
  29. }
  30. } else if (callback === null) {
  31. this._eventMap.delete(event);
  32. }
  33. }
  34. return this;
  35. }
  36. emit(event: string, ...args: any[]) {
  37. if (!this._eventMap.has(event)) {
  38. return false;
  39. }
  40. this._eventMap.get(event).forEach(callback => callback(...args));
  41. return true;
  42. }
  43. }