首页 技术 正文
技术 2022年11月18日
0 收藏 807 点赞 4,651 浏览 982 个字

监听方法:

 // 在任何组件、页面,例如页面 const app = getApp( ); Page({     onLoad: function( ) {
app.watch$('role', ( val, old ) => {
console.log( old, val ); // 此处输出 1, 2
})
}, });

使用方法(触发watch):

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

在根目录的 app.js

 App({     /** 全局store */
globalData: {
role: 1
}, /** 监听函数的对象数组 */
watchCallBack: { }, /** 监听列表 */
watchingKeys: [ ], /** 初始化 */
init: function( ) {
// 全局数据
this.globalData$ = Object.assign({ }, this.globalData );
}, /** 设置全局数据 */
setGlobalData: function( obj ) {
Object.keys( obj ).map( key => {
this.globalData[ key ] = obj[ key ];
});
}, /** watch函数 */
watch$( key, cb ) {
this.watchCallBack = Object.assign({}, this.watchCallBack, {
[key]: this.watchCallBack[ key ] || [ ]
});
this.watchCallBack[ key ].push( cb );
if ( !this.watchingKeys.find( x => x === key )) {
const that = this;
this.watchingKeys.push( key );
Object.defineProperty( this.globalData, key, {
configurable: true,
enumerable: true,
set: function( val ) {
const old = that.globalData$[key];
that.globalData$[ key ] = val;
that.watchCallBack[key].map(func => func( val, old ));
},
get: function( ) {
return that.globalData$[key];
}
});
}
}, });
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902