以下兩種場景,在微信小程序官方并沒有提供類似iOS的NSNotificationCenter 或者 Android的廣播類似的解決方案。
- A頁面 -> B頁面,B頁面完成相關邏輯需要通知A頁面刷新數據(并傳值)
- 通知(廣播)已入棧并且注冊過通知的頁面(并傳值)
一、如果遇到以上的場景,要怎么處理呢?
在github上發(fā)現了WxNotificationCenter,下載地址: https://github.com/icindy/WxNotificationCenter WxNotificationCenter借鑒iOS開發(fā)中的NSNotificationCenter的消息模式進行開發(fā)
簡單的說WxNotificationCenter是實現大跨度的通信機制,可以為兩個無引用關系的兩個對象進行通信,即事件發(fā)出者和響應者可以沒有任何耦合關系。
二、讓我們看看代碼中的使用
- 獲取到 WxNotificationCenter 將WxNotificationCenter.js文件加入項目目錄下
- 頁面中導入
var WxNotificationCenter = require('../../../vendors/WxNotificationCenter.js') - A頁面的Page生命周期中注冊、移除通知,及接收通知后響應的fuction
onLoad: function () {
//注冊通知
var that = this
WxNotificationCenter.addNotification('NotificationName', that.didNotification, that)
},
onUnload: function () {
//移除通知
var that = this
WxNotificationCenter.removeNotification('NotificationName', that)
},
//通知處理
didNotification: function () {
//更新數據
this.setData({
})
},
- B頁面處理完邏輯,發(fā)送通知
//發(fā)送通知(所有注冊過'NotificationName'的頁面都會接收到通知)
WxNotificationCenter.postNotificationName('NotificationName')
三、如何傳值?
obj 為字符串 或者 對象
WxNotificationCenter.postNotificationName('NotificationName',obj)WxNotificationCenter.addNotification('NotificationName', that.didNotification, that)
didNotification: function (obj) {
//拿到值obj
},
四、源碼解析
- 全部源碼只有WxNotificationCenter.js一個文件,通過以下方式引用該文件:
var WxNotificationCenter = require('../../vendors/WxNotificationCenter.js')
- 源碼對外開放三個方法:
module.exports = {
addNotification: addNotification,
removeNotification: removeNotification,
postNotificationName: postNotificationName
}
- 核心源碼
var __notices = [];
var newNotice = {
name: name, //注冊名,一般let在公共類中
selector: selector //對應的通知方法,接受到通知后進行的動作
observer: observe //注冊對象,指Page對象
};
沒錯,只有一個數組! 操作一個對象!
核心思想很簡單,就是利用一個數組緩存對象,通過設置name和注冊對象來確定需要通知或者廣播的對象,并監(jiān)聽通知方法
首先Page對象中調用addNotification(name, selector, observer)方法,將newNotice對象push進數組__notices(可以重復加入);
__notices.push(newNotice);
然后postNotificationName(name, info)方法,將數組__notices中的對象遍歷出來,notice.name === name符合該要求的對象執(zhí)行notice.selector(info);
for (var i = 0; i < __notices.length; i++){
var notice = __notices[i];
if(notice.name === name){
notice.selector(info);
}
}
最后釋放內存,根據各自的業(yè)務邏輯,調用removeNotification(name,observer) 將對應的對象從數組中移除:
if(notice.name === name){
if(notice.observer === observer){
__notices.splice(i,1);
return;
}
}
自己寫了個Demo,感興趣的可以拉一下 https://github.com/hanqingman/WxNotificationCenter-Demo