index.ts 697 B

123456789101112131415161718192021222324252627282930313233
  1. import { router } from "../router";
  2. class Scroller {
  3. list: Map<string, ((top: number) => void)[]> = new Map();
  4. // 触发滚动
  5. emit(top: number) {
  6. const cbs = this.list.get(router.path()) ?? [];
  7. cbs.forEach((cb) => {
  8. cb(top);
  9. });
  10. }
  11. // 监听页面滚动
  12. on(callback: (top: number) => void) {
  13. const path = router.path();
  14. const cbs = this.list.get(path) ?? [];
  15. cbs.push(callback);
  16. this.list.set(path, cbs);
  17. }
  18. // 取消监听页面滚动
  19. off = (callback: (top: number) => void) => {
  20. const path = router.path();
  21. const cbs = this.list.get(path) ?? [];
  22. this.list.set(
  23. path,
  24. cbs.filter((cb) => cb != callback)
  25. );
  26. };
  27. }
  28. export const scroller = new Scroller();