From 8726e3080bd889ea67ceb26f9ca7039025e20452 Mon Sep 17 00:00:00 2001
From: Tevin <tingquanren@163.com>
Date: Thu, 08 Jul 2021 17:16:51 +0800
Subject: [PATCH] 实现页面间通讯公共模块

---
 common/PagePoster.js |   71 +++++++++++++++++++++++++++++++++++
 1 files changed, 71 insertions(+), 0 deletions(-)

diff --git a/common/PagePoster.js b/common/PagePoster.js
new file mode 100644
index 0000000..0ffd4c2
--- /dev/null
+++ b/common/PagePoster.js
@@ -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();
\ No newline at end of file

--
Gitblit v1.9.1