作者:汗青fullstack,來自授權地址
以下兩種場景,在微信小程序官方并沒有提供類似iOS的NSNotificationCenter 或者 Android的廣播類似的解決方案。
-
A頁面 -> B頁面,B頁面完成相關邏輯需要通知A頁面刷新數(shù)據(jù)(并傳值)
-
通知(廣播)已入棧并且注冊過通知的頁面(并傳值)
如果遇到以上的場景,要怎么處理呢?
在github上發(fā)現(xiàn)了WxNotificationCenter,下載地址:https://github.com/icindy/WxNotificationCenter WxNotificationCenter借鑒iOS開發(fā)中的NSNotificationCenter的消息模式進行開發(fā)
簡單的說WxNotificationCenter是實現(xiàn)大跨度的通信機制,可以為兩個無引用關系的兩個對象進行通信,即事件發(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 () {
//更新數(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
},
自己寫了個Demo,感興趣的可以拉一下https://github.com/hanqingman/WxNotificationCenter-Demo
|