WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2021-07-09 d270af0a5ae30d20da42fccb0b33dd023bec3eac
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
68
69
70
71
72
73
74
75
76
77
/**
 * 页面间通讯
 * @author Tevin
 */
 
import Taro from '@tarojs/taro';
import { Tools } from '@components/common/Tools';
 
export class PagePoster {
 
    constructor() {
        this._data = {
            eventors: {},
            events: {},
        };
    }
 
    save(data) {
        const guid = Tools.createGUID();
        Taro.setStorageSync(guid, JSON.stringify(data));
        return guid;
    }
 
    read(id) {
        const data = Taro.getStorageSync(id);
        Taro.removeStorage({ key: id });
        return JSON.parse(data);
    }
 
    createEventor() {
        const that = this;
        const guid = Tools.createGUID();
        this._data.eventors[guid] = {
            id: guid,
            events: new Taro.Events(),
            on(name, callback) {
                if (!this.events) {
                    return;
                }
                this.events.on(name, callback);
            },
            emit(name, data) {
                if (!this.events) {
                    return;
                }
                this.events.trigger(name, data);
            },
            destroy() {
                // 移除所有监听
                this.events.off();
                this.events = null;
                // 解除 link 的绑定
                if (this.linkCB) {
                    this.linkCB(null);
                }
                // 解除引用
                delete that._data.eventors[this.id];
            },
            linkCB: null,
        };
        return this._data.eventors[guid];
    }
 
    linkEventor(guid, linkCB) {
        if (typeof this._data.eventors[guid] === 'undefined') {
            linkCB(null);
        } else {
            const eventor = this._data.eventors[guid];
            eventor.linkCB = linkCB;
            eventor.emit('@linked');
            linkCB(eventor);
        }
    }
 
}
 
export const $pagePoster = new PagePoster();