分享: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