找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 小程序开发 查看内容

微信小程序-通知广播WxNotificationCenter:完成相关逻辑并通知页面刷新数据 ...

作者:模板之家 2018-4-13 15:00 3476人关注

作者:汗青fullstack,来自授权地址 以下两种场景,在微信小程序官方并没有提供类似iOS的NSNotificationCenter 或者 Android的广播类似的解决方案。 A页面 - B页面,B页面完成相关逻辑需要通知

作者:汗青fullstack,来自授权地址 

以下两种场景,在微信小程序官方并没有提供类似iOS的NSNotificationCenter 或者 Android的广播类似的解决方案。

  1. A页面 -> B页面,B页面完成相关逻辑需要通知A页面刷新数据(并传值)
  2. 通知(广播)已入栈并且注册过通知的页面(并传值)
如果遇到以上的场景,要怎么处理呢?

在github上发现了WxNotificationCenter,下载地址:https://github.com/icindy/WxNotificationCenter WxNotificationCenter借鉴iOS开发中的NSNotificationCenter的消息模式进行开发
简单的说WxNotificationCenter是实现大跨度的通信机制,可以为两个无引用关系的两个对象进行通信,即事件发出者和响应者可以没有任何耦合关系。

让我们看看代码中的使用
  1. 获取到 WxNotificationCenter 将WxNotificationCenter.js文件加入项目目录下
  2. 页面中导入
    var WxNotificationCenter = require('../../../vendors/WxNotificationCenter.js')
  3. 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({
    
     })
    },
  4. B页面处理完逻辑,发送通知
    //发送通知(所有注册过'NotificationName'的页面都会接收到通知)
    WxNotificationCenter.postNotificationName('NotificationName')
如何传值?

obj 为字符串 或者 对象

  1. WxNotificationCenter.postNotificationName('NotificationName',obj)
  2. WxNotificationCenter.addNotification('NotificationName', that.didNotification, that)

    didNotification: function (obj) {
      //拿到值obj
    
    },

自己写了个Demo,感兴趣的可以拉一下https://github.com/hanqingman/WxNotificationCenter-Demo



路过

雷人

握手

鲜花

鸡蛋
原作者: 模板之家 来自: 网络收集

全部回复(0)