自定義GlobalThis進(jìn)行數(shù)據(jù)同步
想了解更多關(guān)于開源的內(nèi)容,請(qǐng)?jiān)L問:
1、前言
在OpenHarmony 3.2 Release版本的配套文檔,對(duì)應(yīng)API能力級(jí)別為API 9 Release時(shí),使用globalThis進(jìn)行數(shù)據(jù)同步:在ArkTS引擎實(shí)例內(nèi)部,globalThis是一個(gè)全局對(duì)象,可以被ArkTS引擎實(shí)例內(nèi)的UIAbility組件、ExtensionAbility組件和ArkUI頁(yè)面(Page)訪問。但在OpenHarmony 4.0 Release版本的配套文檔,對(duì)應(yīng)API能力級(jí)別為API 10 Release后,就棄用了globalThis全局對(duì)象,如果我們之前的項(xiàng)目里有用到globalThis全局對(duì)象,而在新的API 10里不能用了,我們是可以通構(gòu)造一個(gè)單例對(duì)象來處理的。這里自定義一下GlobalThis全局對(duì)象,通過在GlobalThis對(duì)象上綁定屬性/方法, 下面通過一個(gè)簡(jiǎn)單實(shí)例,全局存儲(chǔ)context,存儲(chǔ)屬性值,存儲(chǔ)首選項(xiàng)對(duì)象。效果圖如下:
2、自定義GlobalThis單例對(duì)象
import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences';
// 構(gòu)造單例對(duì)象
export class GlobalThis {
private constructor() {}
private static instance: GlobalThis;
// 緩存context
private _uiContexts = new Map<string, common.UIAbilityContext>();
// 緩存屬性值
private _attribute = new Map<string, string>();
// 緩存首選項(xiàng)
private _preferences = new Map<string, Promise<dataPreferences.Preferences>>();
public static getInstance(): GlobalThis {
if (!GlobalThis.instance) {
GlobalThis.instance = new GlobalThis();
}
return GlobalThis.instance;
}
getContext(key: string): common.UIAbilityContext | undefined {
return this._uiContexts.get(key);
}
setContext(key: string, value: common.UIAbilityContext): void {
this._uiContexts.set(key, value);
}
getAttribute(key: string): string | undefined {
return this._attribute.get(key);
}
setAttribute(key: string, value: string): void {
this._attribute.set(key, value);
}
getPreferences(key: string): Promise<dataPreferences.Preferences> | undefined {
return this._preferences.get(key);
}
setPreferences(key: string, value: Promise<dataPreferences.Preferences>): void {
this._preferences.set(key, value);
}
// 其他需要傳遞的內(nèi)容依此擴(kuò)展
}
3、使用說明
在EntryAbility.ets中導(dǎo)入構(gòu)建的單例對(duì)象GlobalThis。
import { GlobalThis } from '../utils/GlobalThis'; // 需要根據(jù)globalThis.ets的路徑自行適配
在onCreate中添加:
GlobalThis.getInstance().setContext("context", this.context);
在Page中使用:
let context: common.UIAbilityContext | undefined = GlobalThis.getInstance().getContext("context");
4、實(shí)現(xiàn)效果圖Demo
效果圖實(shí)例包含兩個(gè)Page, 一個(gè)自定義GlobalThis單例對(duì)象。
在ets目錄下創(chuàng)建utils目錄,并創(chuàng)建GlobalThis.ets文件,代碼如上面。
首頁(yè)面顯示在EntryAbility.ets文件onCreate()方法設(shè)置好的屬性值,context, 首選項(xiàng)數(shù)據(jù)庫(kù).
- onCreate()方法添加代碼如下:
import { GlobalThis } from '../utils/GlobalThis';
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
const PREFERENCES_NAME = 'nutsusPreferences';
const KEY_APP_PRIVACY = 'nutsusKey';
export default class EntryAbility extends UIAbility {
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 緩存context
GlobalThis.getInstance().setContext("context", this.context);
// 緩存作者屬性值
GlobalThis.getInstance().setAttribute("author", "狼哥");
// 緩存組織屬性值
GlobalThis.getInstance().setAttribute("org", "堅(jiān)果派");
let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, PREFERENCES_NAME);
// 緩存首選項(xiàng)Promise
GlobalThis.getInstance().setPreferences("preferences", preferences);
preferences.then((result: dataPreferences.Preferences) => {
// 存儲(chǔ)文本到nutsusKey主鍵
result.putSync(KEY_APP_PRIVACY, "堅(jiān)果派由堅(jiān)果創(chuàng)建,團(tuán)隊(duì)擁有8個(gè)華為HDE,3個(gè)HSD,以及若干其他領(lǐng)域的三十余位萬粉博主運(yùn)營(yíng)。");
console.log('xxx')
}).catch((err: BusinessError) => {
console.error('xx put the preferences failed, err: ' + err);
});
}
}
- 首頁(yè)面使用GlobalThis對(duì)象,代碼如下:
- 導(dǎo)入構(gòu)建GlobalThis單例對(duì)象
import { GlobalThis } from '../utils/GlobalThis';
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
import common from '@ohos.app.ability.common';
const KEY_APP_PRIVACY = 'nutsusKey';
首頁(yè)面顯示函數(shù)時(shí),從GlobalThis對(duì)象獲取數(shù)據(jù)
onPageShow() {
this.author = GlobalThis.getInstance().getAttribute("author");
this.org = GlobalThis.getInstance().getAttribute("org");
let context: common.UIAbilityContext | undefined = GlobalThis.getInstance().getContext("context");
if (context != undefined) {
this.label = context.abilityInfo.bundleName;
}
let preferences: Promise<dataPreferences.Preferences> | undefined = GlobalThis.getInstance().getPreferences("preferences")
if (preferences != undefined) {
preferences.then((result: dataPreferences.Preferences) => {
result.get(KEY_APP_PRIVACY, "").then((data) => {
this.message = String(data);
})
}).catch((err: BusinessError) => {
console.error('xx get the preferences failed, err: ' + err);
})
}
}
首頁(yè)面布局代碼如下:
Column({space: 50}) {
Text(`[${this.org}] ${this.author}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Divider()
Text(`${this.message}`)
.fontSize(20)
Button('跳轉(zhuǎn)下一頁(yè)')
.width('80%')
.height(50)
.onClick(() => {
router.pushUrl({
url: 'pages/Second'
})
})
Text(`獲取Context的bundleName: ${this.label}`)
.width('100%')
.margin({top: 50})
}
.width('100%')
.height('100%')
.padding(20)
第二頁(yè)面使用GlobalThis對(duì)象,代碼如下:
- 導(dǎo)入構(gòu)建GlobalThis單例對(duì)象
import { GlobalThis } from '../utils/GlobalThis';
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';
const KEY_APP_PRIVACY = 'nutsusKey';
第二頁(yè)面頁(yè)面加載前函數(shù)時(shí),從GlobalThis獲取數(shù)據(jù)
@State author: string | undefined = GlobalThis.getInstance().getAttribute("author");
@State org: string | undefined = GlobalThis.getInstance().getAttribute("org");
@State message: string = "";
private preferences: Promise<dataPreferences.Preferences> | undefined = GlobalThis.getInstance().getPreferences("preferences")
aboutToAppear() {
if (this.preferences != undefined) {
this.preferences.then((result: dataPreferences.Preferences) => {
result.get(KEY_APP_PRIVACY, "").then((data) => {
this.message = String(data);
})
}).catch((err: BusinessError) => {
console.error('xx get the preferences failed, err: ' + err);
})
}
}
第二頁(yè)面修改數(shù)據(jù)代碼如下:
onChange() {
if (this.author != undefined) {
GlobalThis.getInstance().setAttribute("author", this.author);
}
if (this.preferences != undefined) {
this.preferences.then((result: dataPreferences.Preferences) => {
result.putSync(KEY_APP_PRIVACY, this.message)
}).catch((err: BusinessError) => {
console.error('xx set the preferences failed, err: ' + err);
})
}
promptAction.showToast({
message: '修改成功^_^',
duration: 2000
});
}
第二頁(yè)面布局代碼如下:
Column({space: 50}) {
TextInput({text: this.author})
.onChange((value) => {
this.author = value;
})
Text(`[${this.org}]`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
TextArea({text: this.message})
.onChange((value) => {
this.message = value;
})
Row({space: 50}) {
Button('返回')
.width(100)
.onClick(() => {
router.back();
})
Button('修改')
.width(100)
.onClick(() => {
this.onChange()
})
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
.width('100%')
.height('100%')
.padding(20)
5、總結(jié)
雖然在OpenHarmony 4.0 Release,對(duì)應(yīng)API能力級(jí)別為API 10 Release后不能直接使用globalThis全局對(duì)象,但通過自定義單例對(duì)象后,還是很方便實(shí)現(xiàn)屬性/方法綁定,在UIAbility和Page之間、UIAbility和UIAbility之間、UIAbility和ExtensionAbility之間都可以使用自構(gòu)建GlobalThis單例對(duì)象上綁定屬性/方法,可以實(shí)現(xiàn)之間的數(shù)據(jù)同步。