自定义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-05-05 14:34:45

Oracle数据库

2010-03-16 17:39:36

Java多线程锁

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 自定义信号

2021-05-08 07:51:07

Vue框架前端

2014-04-02 13:27:29

iOSNSArray对象

2012-02-02 13:45:28

JavaJSP

2009-07-06 16:59:26

JSP自定义标签

2011-12-16 14:23:51

Java

2009-06-08 20:13:36

Eclipse自定义控

2013-04-01 14:35:10

Android开发Android自定义x

2015-01-14 15:06:48

定义相机

2021-11-23 15:06:42

Kubernetes 运维开源
点赞
收藏

51CTO技术栈公众号