
CrossPage.js 是一个简单的页面间通信模块,包括 CrossPageExchangeItem 类和 CrossPageExchange 类。
CrossPageExchangeItem 类用于创建一个新的通信项 exchangeItem,CrossPageExchange 类拥有 createItem/getItem/deleteItem 静态方法。
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
|
class CrossPageExchangeItem { constructor(id) { this.id = id; this.setDataHandler = null; this.cancelHandler = null; } getId() { return this.id; }
onSetData(cb) { this.setDataHandler = cb; }
setData(data) { if (typeof this.setDataHandler === 'function') { this.setDataHandler(data); } }
onCancel(cb) { this.cancelHandler = cb; }
cancel() { if (typeof this.cancelHandler === 'function') { this.cancelHandler(); } }
remove() { this.setDataHandler = null; CrossPageExchange.deleteItem(this.id); } }
class CrossPageExchange { static latestId = 0; static items = new Object(null);
static createItem() { let newItem = new CrossPageExchangeItem(this.latestId); this.items[this.latestId] = newItem; this.latestId++;
return newItem; }
static getItem(id) { return this.items[id] || null; }
static deleteItem(id) { delete this.items[id]; } }
module.exports = { CrossPageExchange, };
|
WaitObject 类,它通过 Promise 提供了一种等待的机制。
wait 方法是一个异步函数,它等待 this.p 的状态被解决(resolved)。通过 await this.p ,函数回暂停执行,直到 this.p 被解决,然后返回被解决的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class WaitObject { constructor() { this.p = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); }
async wait() { return await this.p; } }
module.exports = { WaitObject, };
|
小程序异步模型

