liukangdong
2024-09-29 b2d360d9113b6955287108ca9e90d76a1f3c1419
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
let isLogin = false;
 
// 发布订阅模式
class Publisher {
  constructor() {
    this.map = new Map();
  }
  on(key, callback) {
    let arr = this.map.get(key) || [];
    arr.push(callback);
    this.map.set(key, arr);
  }
  emit(key, data = {}) {
    if (this.map.has(key)) {
      this.map.get(key).forEach((item) => {
        item.call(this, data);
      });
    }
  }
}
 
let publisher = new Publisher();
 
// 页面扩展
const oldPage = Page;
Page = function (pageParams) {
  const { onLoad, onShow, onReady } = pageParams;
 
  pageParams.onLoad = function (params) {
    // 判断是否登陆
    if (isLogin) {
      onLoad && onLoad.call(this, params);
    } else {
      publisher.on("login", () => {
        isLogin = true;
        onLoad && onLoad.call(this, params);
      });
    }
  };
 
  pageParams.onShow = function () {
    // 判断是否登陆
    if (isLogin) {
      onShow && onShow.call(this);
    } else {
      publisher.on("login", () => {
        onShow && onShow.call(this);
      });
    }
  };
 
  pageParams.onReady = function () {
    // 判断是否登陆
    if (isLogin) {
      onReady && onReady.call(this);
    } else {
      publisher.on("login", () => {
        onReady && onReady.call(this);
      });
    }
  };
  return oldPage(pageParams);
};
 
module.exports = {
  publisher,
};