WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2021-07-08 8726e3080bd889ea67ceb26f9ca7039025e20452
实现页面间通讯公共模块
1 files added
71 ■■■■■ changed files
common/PagePoster.js 71 ●●●●● patch | view | raw | blame | history
common/PagePoster.js
New file
@@ -0,0 +1,71 @@
/**
 * 页面间通讯
 * @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) {
                this.events.on(name, callback);
            },
            emit(name, data) {
                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();