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 });
  • 相关阅读:
    1024 Palindromic Number (25分)
    Fliptile POJ 3279
    ASP.NET MVC中的TempData机制
    Entity Framework中的批量提交与分布式事务处理
    MongoDB学习笔记
    在Entity Framework中实现指定字段更新
    bootstrap 对话框调用 iframe
    MVC PartialView视图使用心得
    何时使用PartialView方法
    ASP.NET MVC3调用PartialView的几种方式
  • 原文地址:https://www.cnblogs.com/BestMePeng/p/xcx_watch_globaldata.html
Copyright © 2011-2022 走看看