微信小程序中实现一对多发消息详解及实例代码
微信小程序中实现一对多发消息详解及实例代码
微信小程序中各个界面之间的传值和通知比较蛋疼。所以模仿了iOS中的通知中心,在微信小程序中写了一套类似的通知中心。
通知中心可以做到:1对多发消息,传递object。使用十分简洁。
使用时,在需要接收消息的界面注册一个通知名。然后在需要发消息的界面post这个通知名就可以了。可以在多个界面注册同一个通知名。这样就可以1对多发消息。
使用方法:
1:在app.js中引用notification.js
varnotificationCenter=require('/utils/notification.js');//这里请改为你的绝对路径
2:在app.js中添加:
App({
onLaunch:function(){
this.notificationCenter=notificationCenter.center();
},
notificationCenter:null,
})
3:接收通知的page.js中注册
PageA.js:
varapp=getApp();
Page({
onLoad:function(options){
app.notificationCenter.register("一个通知名称",this,"didReceviceAnyNotification");
},
didReceviceAnyNotification:function(name,content){
console.log("接收到了通知:",name,content);
},
})
4:发出通知的page.js中
PageB.js任意函数
varapp=getApp();
Page({
anyFunction:function(){
app.notificationCenter.post("通知名称",{
//任意通知object
});
},
})
实现:
文件下载:http://xiazai.jb51.net/201702/yuanma/wxappNotificationCenter-master(jb51.net).rar
varnotificationCenter={
notificationCenter:{},
//向通知中心注册一个监听者。
//name:监听的通知名称
//observer:监听者
//action:监听者收通知时调用的方法名,
//func:监听者收到通知时调用的函数,
//actionfunc2选1
register:function(name,observer,action,func){
if(!name||!observer)return;
if(!action&&!func)return;
console.log("注册通知:",name,observer);
varcenter=this.notificationCenter;
varobjects=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;
varcenter=this.notificationCenter;
varobjects=center[name];
if(!objects){
return;
}
varidx;
varobject;
for(idx=0;idx<objects.length;idx++){
varobj=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);
varcenter=this.notificationCenter;
varobjects=center[name];
if(!objects){
objects=[];
}
objects.forEach(function(object){
varobserver=object.observer;
varaction=object.action;
varfunc=object.func;
if(observer&&action){
func=observer[action];
}
func(notification);
});
console.log("完成向",objects.length,"个监听者发出通知:",name);
}
}
functioncenter(){
returnnotificationCenter;
}
module.exports.center=center;
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!