|
@@ -3,14 +3,22 @@ class MessageCenter {
|
|
|
constructor() {
|
|
|
// 缓存事件队列
|
|
|
this.messageCallbackMap = new Map();
|
|
|
+ this.messageFailbackMap = new Map();
|
|
|
this.init()
|
|
|
}
|
|
|
|
|
|
- send({ actionType, data }) {
|
|
|
+ send({ actionType, data, callback, overTime, failback }) {
|
|
|
window.parent.postMessage({
|
|
|
actionType,
|
|
|
data
|
|
|
}, '*');
|
|
|
+ if (data.messageID && callback) {
|
|
|
+ // 带回调callback 的message, 要求携带messageID,callback,failback等
|
|
|
+ this.listen(`${actionType}-${data.messageID}`, callback)
|
|
|
+ if (failback) {
|
|
|
+ this.addFailback(`${actionType}-${data.messageID}`, overTime, failback)
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
listen(actionType, callback) {
|
|
@@ -22,9 +30,25 @@ class MessageCenter {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- init() {
|
|
|
+ addFailback(actionType, overTime=2000, failback) {
|
|
|
+ let failbackQuene = this.messageFailbackMap.get(actionType);
|
|
|
+ if (failbackQuene && failbackQuene.failCallbackList) {
|
|
|
+ failbackQuene.failCallbackList.push(
|
|
|
+ failback
|
|
|
+ )
|
|
|
+ } else {
|
|
|
+ this.messageFailbackMap.set(actionType, {
|
|
|
+ time: new Date().getTime(),
|
|
|
+ overTime,
|
|
|
+ failCallbackList: [failback]
|
|
|
+ })
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ init() {
|
|
|
window.addEventListener('message', (e) => {
|
|
|
const { actionType, data } = e.data;
|
|
|
+ this.messageFailbackMap.delete(actionType);
|
|
|
const quene = this.messageCallbackMap.get(actionType) || [];
|
|
|
let index = 0;
|
|
|
while (index < quene.length) {
|
|
@@ -33,6 +57,24 @@ class MessageCenter {
|
|
|
index++
|
|
|
}
|
|
|
})
|
|
|
+ setInterval(() => {
|
|
|
+ // 轮询查看有无超期的message信息
|
|
|
+ const now = new Date().getTime();
|
|
|
+ for (let item of this.messageFailbackMap.values()) {
|
|
|
+ if (now - item.time > item.overTime) {
|
|
|
+ let index = 0;
|
|
|
+ while (index < item.failCallbackList.length) {
|
|
|
+ const callback = item.failCallbackList[index];
|
|
|
+ callback({
|
|
|
+ error: 0,
|
|
|
+ msg: "message 超时错误"
|
|
|
+ })
|
|
|
+ index++
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }, 1000)
|
|
|
}
|
|
|
}
|
|
|
|