zoukankan      html  css  js  c++  java
  • 分享: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 });
  • 相关阅读:
    如何计算时间复杂度
    注意线程
    java中一个类要当作线程来使用有两种方法
    压缩和解压
    init [0123456]
    linux文件目录
    为什么使用combiner?【Hadoop】
    JAVA标识符
    关键字:java
    转 java 中int String类型转换
  • 原文地址:https://www.cnblogs.com/BestMePeng/p/xcx_watch_globaldata.html
Copyright © 2011-2022 走看看