分享: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 });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM