偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

自定義GlobalThis進(jìn)行數(shù)據(jù)同步

系統(tǒng) OpenHarmony
這里自定義一下GlobalThis全局對象,通過在GlobalThis對象上綁定屬性/方法, 下面通過一個簡單實例,全局存儲context,存儲屬性值,存儲首選項對象。

想了解更多關(guān)于開源的內(nèi)容,請訪問:

51CTO 鴻蒙開發(fā)者社區(qū)

https://ost.51cto.com

1、前言

在OpenHarmony 3.2 Release版本的配套文檔,對應(yīng)API能力級別為API 9 Release時,使用globalThis進(jìn)行數(shù)據(jù)同步:在ArkTS引擎實例內(nèi)部,globalThis是一個全局對象,可以被ArkTS引擎實例內(nèi)的UIAbility組件、ExtensionAbility組件和ArkUI頁面(Page)訪問。但在OpenHarmony 4.0 Release版本的配套文檔,對應(yīng)API能力級別為API 10 Release后,就棄用了globalThis全局對象,如果我們之前的項目里有用到globalThis全局對象,而在新的API 10里不能用了,我們是可以通構(gòu)造一個單例對象來處理的。這里自定義一下GlobalThis全局對象,通過在GlobalThis對象上綁定屬性/方法, 下面通過一個簡單實例,全局存儲context,存儲屬性值,存儲首選項對象。效果圖如下:


2、自定義GlobalThis單例對象

import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences';

// 構(gòu)造單例對象
export class GlobalThis {
  private constructor() {}
  private static instance: GlobalThis;
  // 緩存context
  private _uiContexts = new Map<string, common.UIAbilityContext>();
  // 緩存屬性值
  private _attribute = new Map<string, string>();
  // 緩存首選項
  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)容依此擴展
}

3、使用說明

在EntryAbility.ets中導(dǎo)入構(gòu)建的單例對象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、實現(xiàn)效果圖Demo

效果圖實例包含兩個Page, 一個自定義GlobalThis單例對象。

在ets目錄下創(chuàng)建utils目錄,并創(chuàng)建GlobalThis.ets文件,代碼如上面。

首頁面顯示在EntryAbility.ets文件onCreate()方法設(shè)置好的屬性值,context, 首選項數(shù)據(jù)庫.

  • 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", "堅果派");

    let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, PREFERENCES_NAME);
    // 緩存首選項Promise
    GlobalThis.getInstance().setPreferences("preferences", preferences);
    preferences.then((result: dataPreferences.Preferences) => {
      // 存儲文本到nutsusKey主鍵
      result.putSync(KEY_APP_PRIVACY, "堅果派由堅果創(chuàng)建,團(tuán)隊擁有8個華為HDE,3個HSD,以及若干其他領(lǐng)域的三十余位萬粉博主運營。");
      console.log('xxx')
    }).catch((err: BusinessError) => {
      console.error('xx put the preferences failed, err: ' + err);
    });
  }
}
  • 首頁面使用GlobalThis對象,代碼如下:
  • 導(dǎo)入構(gòu)建GlobalThis單例對象
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';
首頁面顯示函數(shù)時,從GlobalThis對象獲取數(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);
        })
    }
  }
首頁面布局代碼如下:
Column({space: 50}) {
      Text(`[${this.org}] ${this.author}`)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)

      Divider()
      Text(`${this.message}`)
        .fontSize(20)

      Button('跳轉(zhuǎn)下一頁')
        .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)

第二頁面使用GlobalThis對象,代碼如下:

  • 導(dǎo)入構(gòu)建GlobalThis單例對象
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';
第二頁面頁面加載前函數(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);
      })
    }
  }
第二頁面修改數(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
    });
  }
第二頁面布局代碼如下:
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,對應(yīng)API能力級別為API 10 Release后不能直接使用globalThis全局對象,但通過自定義單例對象后,還是很方便實現(xiàn)屬性/方法綁定,在UIAbility和Page之間、UIAbility和UIAbility之間、UIAbility和ExtensionAbility之間都可以使用自構(gòu)建GlobalThis單例對象上綁定屬性/方法,可以實現(xiàn)之間的數(shù)據(jù)同步。

想了解更多關(guān)于開源的內(nèi)容,請訪問:

51CTO 鴻蒙開發(fā)者社區(qū)

https://ost.51cto.com

責(zé)任編輯:jianghua 來源: 51CTO 鴻蒙開發(fā)者社區(qū)
相關(guān)推薦

2010-03-17 18:21:54

Java多線程靜態(tài)數(shù)據(jù)

2015-02-12 15:33:43

微信SDK

2010-03-01 11:10:41

WCF綁定元素

2010-03-16 17:39:36

Java多線程鎖

2015-02-12 15:38:26

微信SDK

2010-05-05 14:34:45

Oracle數(shù)據(jù)庫

2009-08-28 17:45:19

C#自定義數(shù)據(jù)

2009-08-03 16:37:49

C#異常類

2016-11-16 21:55:55

源碼分析自定義view androi

2016-12-26 15:25:59

Android自定義View

2011-06-23 10:49:13

Qt 自定義信號

2012-02-02 13:45:28

JavaJSP

2014-04-02 13:27:29

iOSNSArray對象

2025-02-07 14:52:11

2021-05-08 07:51:07

Vue框架前端

2009-07-06 16:59:26

JSP自定義標(biāo)簽

2010-09-14 16:47:23

SQL自定義函數(shù)

2023-09-06 10:33:40

夜鶯監(jiān)控數(shù)據(jù)庫

2021-12-28 15:38:46

Traefik中間件插件

2013-04-19 10:14:24

點贊
收藏

51CTO技術(shù)棧公眾號