Event.ts 1.6 KB

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