监听方法:
// 在任何组件、页面,例如页面 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];
}
});
}
}, });