分享:50行代码监听watch小程序的globalData

监听方法:

 1 // 在任何组件、页面,例如页面
 2 
 3 const app = getApp( );
 4 
 5 Page({
 6 
 7     onLoad: function( ) {
 8       app.watch$('role', ( val, old ) => {
 9         console.log( old, val ); //  此处输出 1, 2
10       })
11     },
12 
13 });

 

使用方法(触发watch):

1 // 在任何组件、页面,例如页面
2 
3 const app = getApp( );
4 
5 app.setGlobalData({
6    role: 2
7 })

 

在根目录的 app.js

 1 App({
 2 
 3     /** 全局store */
 4     globalData: {
 5       role: 1
 6     },
 7 
 8     /** 监听函数的对象数组 */
 9     watchCallBack: { },
10 
11     /** 监听列表 */
12     watchingKeys: [ ],
13 
14     /** 初始化 */
15     init: function( ) {
16       // 全局数据
17       this.globalData$ = Object.assign({ }, this.globalData );
18     },
19 
20     /** 设置全局数据 */
21     setGlobalData: function( obj ) {
22       Object.keys( obj ).map( key => {
23         this.globalData[ key ] = obj[ key ];
24       });
25     },
26 
27     /** watch函数 */
28     watch$( key, cb ) {
29       this.watchCallBack = Object.assign({}, this.watchCallBack, {
30         [key]: this.watchCallBack[ key ] || [ ]
31       });
32       this.watchCallBack[ key ].push( cb );
33       if ( !this.watchingKeys.find( x => x === key )) {
34         const that = this;
35         this.watchingKeys.push( key );
36         Object.defineProperty( this.globalData, key, {
37           configurable: true,
38           enumerable: true,
39           set: function( val ) {
40             const old = that.globalData$[key];
41             that.globalData$[ key ] = val;
42             that.watchCallBack[key].map(func => func( val, old ));
43           },
44           get: function( ) {
45             return that.globalData$[key];
46           }
47         });
48       }
49     },
50   
51 });

 

转载于:https://www.cnblogs.com/BestMePeng/p/xcx_watch_globaldata.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值