以下兩種場景黎泣,在微信小程序官方并沒有提供類似iOS的NSNotificationCenter 或者 Android的廣播類似的解決方案件炉。
- A頁面 -> B頁面纫事,B頁面完成相關(guān)邏輯需要通知A頁面刷新數(shù)據(jù)(并傳值)
- 通知(廣播)已入棧并且注冊過通知的頁面(并傳值)
一、如果遇到以上的場景览露,要怎么處理呢荧琼?
在github上發(fā)現(xiàn)了WxNotificationCenter,下載地址: https://github.com/icindy/WxNotificationCenter WxNotificationCenter借鑒iOS開發(fā)中的NSNotificationCenter的消息模式進(jìn)行開發(fā)
簡單的說WxNotificationCenter是實(shí)現(xiàn)大跨度的通信機(jī)制,可以為兩個無引用關(guān)系的兩個對象進(jìn)行通信铭腕,即事件發(fā)出者和響應(yīng)者可以沒有任何耦合關(guān)系。
二多糠、讓我們看看代碼中的使用
- 獲取到 WxNotificationCenter 將WxNotificationCenter.js文件加入項(xiàng)目目錄下
- 頁面中導(dǎo)入
var WxNotificationCenter = require('../../../vendors/WxNotificationCenter.js')
- A頁面的Page生命周期中注冊累舷、移除通知,及接收通知后響應(yīng)的fuction
onLoad: function () {
//注冊通知
var that = this
WxNotificationCenter.addNotification('NotificationName', that.didNotification, that)
},
onUnload: function () {
//移除通知
var that = this
WxNotificationCenter.removeNotification('NotificationName', that)
},
//通知處理
didNotification: function () {
//更新數(shù)據(jù)
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 //對應(yīng)的通知方法怜俐,接受到通知后進(jìn)行的動作
observer: observe //注冊對象身堡,指Page對象
};
沒錯,只有一個數(shù)組拍鲤! 操作一個對象贴谎!
核心思想很簡單,就是利用一個數(shù)組緩存對象季稳,通過設(shè)置name和注冊對象來確定需要通知或者廣播的對象擅这,并監(jiān)聽通知方法
首先Page對象中調(diào)用addNotification(name, selector, observer)
方法,將newNotice
對象push進(jìn)數(shù)組__notices
(可以重復(fù)加入)景鼠;
__notices.push(newNotice);
然后postNotificationName(name, info)
方法仲翎,將數(shù)組__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);
}
}
最后釋放內(nèi)存铛漓,根據(jù)各自的業(yè)務(wù)邏輯溯香,調(diào)用removeNotification(name,observer)
將對應(yīng)的對象從數(shù)組中移除:
if(notice.name === name){
if(notice.observer === observer){
__notices.splice(i,1);
return;
}
}
自己寫了個Demo,感興趣的可以拉一下 https://github.com/hanqingman/WxNotificationCenter-Demo