成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

自定義GlobalThis進行數據同步

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

想了解更多關于開源的內容,請訪問:

51CTO 鴻蒙開發者社區

https://ost.51cto.com

1、前言

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


2、自定義GlobalThis單例對象

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

// 構造單例對象
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);
  }

  // 其他需要傳遞的內容依此擴展
}

3、使用說明

在EntryAbility.ets中導入構建的單例對象GlobalThis。

import { GlobalThis } from '../utils/GlobalThis'; // 需要根據globalThis.ets的路徑自行適配

在onCreate中添加:

GlobalThis.getInstance().setContext("context", this.context);

在Page中使用:

let context: common.UIAbilityContext | undefined = GlobalThis.getInstance().getContext("context");

4、實現效果圖Demo

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

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

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

  • 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, "堅果派由堅果創建,團隊擁有8個華為HDE,3個HSD,以及若干其他領域的三十余位萬粉博主運營。");
      console.log('xxx')
    }).catch((err: BusinessError) => {
      console.error('xx put the preferences failed, err: ' + err);
    });
  }
}
  • 首頁面使用GlobalThis對象,代碼如下:
  • 導入構建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';
首頁面顯示函數時,從GlobalThis對象獲取數據
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('跳轉下一頁')
        .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對象,代碼如下:

  • 導入構建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';
第二頁面頁面加載前函數時,從GlobalThis獲取數據
@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);
      })
    }
  }
第二頁面修改數據代碼如下:
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、總結

雖然在OpenHarmony 4.0 Release,對應API能力級別為API 10 Release后不能直接使用globalThis全局對象,但通過自定義單例對象后,還是很方便實現屬性/方法綁定,在UIAbility和Page之間、UIAbility和UIAbility之間、UIAbility和ExtensionAbility之間都可以使用自構建GlobalThis單例對象上綁定屬性/方法,可以實現之間的數據同步。

想了解更多關于開源的內容,請訪問:

51CTO 鴻蒙開發者社區

https://ost.51cto.com

責任編輯:jianghua 來源: 51CTO 鴻蒙開發者社區
相關推薦

2010-03-17 18:21:54

Java多線程靜態數據

2015-02-12 15:33:43

微信SDK

2010-03-01 11:10:41

WCF綁定元素

2015-02-12 15:38:26

微信SDK

2010-03-16 17:39:36

Java多線程鎖

2010-05-05 14:34:45

Oracle數據庫

2009-08-28 17:45:19

C#自定義數據

2009-08-03 16:37:49

C#異常類

2016-12-26 15:25:59

Android自定義View

2016-11-16 21:55:55

源碼分析自定義view androi

2011-06-23 10:49:13

Qt 自定義信號

2012-02-02 13:45:28

JavaJSP

2025-02-07 14:52:11

2021-05-08 07:51:07

Vue框架前端

2014-04-02 13:27:29

iOSNSArray對象

2009-07-06 16:59:26

JSP自定義標簽

2022-04-24 15:17:56

鴻蒙操作系統

2013-04-01 14:35:10

Android開發Android自定義x

2021-11-23 15:06:42

Kubernetes 運維開源

2011-12-16 14:23:51

Java
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 天天宗合网 | 一级黄色片网址 | 黄色免费在线网址 | 欧美日韩中文字幕 | 91在线电影| h视频免费在线观看 | 欧美激情在线观看一区二区三区 | 一区二区三区欧美在线 | 日韩成人免费视频 | 自拍视频一区二区三区 | 五月天婷婷久久 | 午夜久久久 | 中文字幕亚洲视频 | 欧美日韩高清在线一区 | 国产一区二区电影 | 中文字幕日韩三级 | 99在线免费观看视频 | 日韩中文电影 | 亚洲精品字幕 | av一区二区三区四区 | 亚洲精品久久久久久久久久久久久 | 精品在线免费观看视频 | 91福利在线观看 | 91精品国产综合久久久久久漫画 | 看一级黄色毛片 | 欧美黑人一区二区三区 | 狠狠爱视频 | 婷婷综合色 | 精品欧美乱码久久久久久 | 羞羞视频在线观看 | 美女网站视频免费黄 | 精品久久网 | 成人网在线观看 | 日本三级在线 | 日本在线小视频 | 精品国产青草久久久久96 | 国产精品久久国产精品久久 | 国产一区二区三区在线视频 | 国产专区在线 | 欧美成人一区二区三区 | 日韩一级精品视频在线观看 |