/** * 页面间通讯 * @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() { if (!this.events) { return; } // 移除所有监听 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; linkCB(eventor); setTimeout(() => { eventor.emit('@linked'); }, 0); } } } export const $pagePoster = new PagePoster();