/**
 * 本 Behavior 会在小程序 data 添加 globalData 的属性，并且添加一个 setGlobalData 的方法，例子：
 * js: this.setGlobalData({hello: 'world'});
 * js: this.setGlobalDataAndStorage({hello: 'world'}); // 会写入缓存
 * wxml: {{ globalData.hello }}
 * watch: "globalData.hello": function(val, oldVal) {...}
 */ export let globalDataStore = { } ; try { const gloabalData = wx . getStorageSync ( "gloabalData" ) ; if ( gloabalData ) { globalDataStore = { ... gloabalData } ; } } catch ( error ) { console . error ( "gloabalData getStorageSync error" , "e =" , error ) ; } let globalCount = 0 ; export default Behavior ( { data : { globalData : Object . assign ( { } , globalDataStore ) } , lifetimes : { attached ( ) { ( this as any ) . __setGlobalDataCount = globalCount ; ( this as any ) . setData ( { globalData : Object . assign ( { } , ( this as any ) . data . globalData || { } , globalDataStore ) } ) ; } } , pageLifetimes : { show ( ) { if ( ( this as any ) . __setGlobalDataCount != globalCount ) { ( this as any ) . __setGlobalDataCount = globalCount ; this . setGlobalData ( Object . assign ( { } , globalDataStore ) ) ; } } } , methods : { setGlobalData ( obj ) { globalCount = globalCount + 1 ; ( this as any ) . __setGlobalDataCount = ( this as any ) . __setGlobalDataCount + 1 ; obj = obj || { } ; let outObj = Object . keys ( obj ) . reduce ( ( sum , key ) => { let _key = "globalData." + key ; sum [ _key ] = obj [ key ] ; return sum ; } , { } ) ; ( this as any ) . setData ( outObj , ( ) => { globalDataStore = ( this as any ) . data . globalData ; } ) ; } , setGlobalDataAndStorage ( obj ) { this . setGlobalData ( obj ) ; try { let gloabalData = wx . getStorageSync ( "gloabalData" ) ; if ( gloabalData ) { gloabalData = { ... gloabalData , ... obj } ; } else { gloabalData = { ... obj } ; } wx . setStorageSync ( "gloabalData" , gloabalData ) ; } catch ( e ) { console . error ( "gloabalData setStorageSync error" , "e =" , e ) ; } } } } ) ;