微信小程序中實現一對多發消息詳解及實例代碼
微信小程序中各個界面之間的傳值和通知比較蛋疼。所以模仿了iOS中的通知中心,在微信小程序中寫了一套類似的通知中心。
通知中心可以做到:1對多發消息,傳遞object。使用十分簡潔。
使用時,在需要接收消息的界面注冊一個通知名。然后在需要發消息的界面post這個通知名就可以了。可以在多個界面注冊同一個通知名。這樣就可以1對多發消息。
使用方法:
1:在app.js中引用notification.js
var notificationCenter = require('/utils/notification.js'); //這里請改為你的絕對路徑
2:在app.js中添加:
App({ onLaunch: function (){ this.notificationCenter = notificationCenter.center(); }, notificationCenter:null,})
3: 接收通知的page.js中注冊
PageA.js:
var app = getApp();Page({ onLoad:function(options){ app.notificationCenter.register("一個通知名稱",this,"didReceviceAnyNotification"); }, didReceviceAnyNotification:function(name,content){ console.log("接收到了通知:",name, content); },})
4: 發出通知的page.js中
PageB.js 任意函數
var app = getApp();Page({ anyFunction:function(){ app.notificationCenter.post("通知名稱",{ //任意通知object }) ; },})
實現:
文件下載:http://xiazai.VeVB.COm/201702/yuanma/wxappNotificationCenter-master(VeVB.COm).rar
var notificationCenter = {notificationCenter:{},// 向通知中心注冊一個監聽者。// name: 監聽的通知名稱// observer: 監聽者// action: 監聽者收通知時調用的方法名,// func: 監聽者收到通知時調用的函數,// action func 2選1register:function(name,observer,action,func){ if (!name || !observer) return; if (!action && !func) return; console.log("注冊通知:",name,observer); var center = this.notificationCenter; var objects = center[name]; if (!objects){ objects = []; } this.remove(name,observer); objects.push({ observer:observer, action:action, func:func }); center[name] = objects;},// 從通知中心移除一個監聽者remove:function(name,observer){ if (!name || !observer) return; var center = this.notificationCenter; var objects = center[name]; if (!objects){ return; } var idx; var object; for(idx = 0;idx<objects.length;idx++){ var obj = objects[idx]; if (obj.observer == observer){ object = obj; break; } } if (object){ objects.splice(idx,1); } center[name] = objects;},// 通過通知中心發出通知// name: 通知名稱// notification: 通知內容post:function(name,notification){ if (!name) return; console.log("準備發出通知:",name,notification); var center = this.notificationCenter; var objects = center[name]; if (!objects){ objects = []; } objects.forEach(function(object){ var observer = object.observer; var action = object.action; var func = object.func; if (observer && action){ func = observer[action]; } func(notification); }); console.log("完成向 ",objects.length," 個監聽者發出通知:",name);}}function center(){ return notificationCenter;}module.exports.center = center;
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答