responsiveObserve.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const responsiveMap: { [key: string]: string } = {
  2. xs: "(max-width: 575px)",
  3. sm: "(min-width: 576px)",
  4. md: "(min-width: 768px)",
  5. lg: "(min-width: 992px)",
  6. xl: "(min-width: 1200px)",
  7. xxl: "(min-width: 1600px)",
  8. xxxl: "(min-width: 2000px)",
  9. };
  10. export class responsiveObserve {
  11. matchHandlers = {} as { [key: string]: any };
  12. unregister() {
  13. Object.keys(responsiveMap).forEach((screen) => {
  14. const matchMediaQuery = responsiveMap[screen];
  15. const handler = this.matchHandlers[matchMediaQuery];
  16. if (handler) {
  17. handler.mql.removeEventListener("change", handler.listener);
  18. }
  19. });
  20. this.matchHandlers = {};
  21. }
  22. register(cb: any) {
  23. Object.keys(responsiveMap).forEach((screen) => {
  24. const matchMediaQuery = responsiveMap[screen];
  25. const listener = (e: MediaQueryListEvent) => {
  26. console.log(e);
  27. if (e.matches) {
  28. cb && cb(screen);
  29. }
  30. };
  31. const mql = window.matchMedia(matchMediaQuery);
  32. if (mql.matches) {
  33. cb && cb(screen);
  34. }
  35. this.matchHandlers[matchMediaQuery] = {
  36. mql: mql,
  37. listener: listener,
  38. };
  39. mql.addEventListener("change", listener);
  40. });
  41. }
  42. }