技术需求:使用watchUtils类,whenTrue相关方法,监测属性。
业务需求:地图类库中,需要读内网的一个接口,判断网络是否为内网,以实现在内网环境下访问内网服务器中更多的地图资源。计划通过一个标识,通过xhr请求接口后设置该标识。之后,地图相关函数,在执行之前判断一下该变量,是否为true,防止因为异步导致的一些变量没有完成初始化。
自定义Accessor类
- /**
- * 20220727
- * 地图初始化对象监控 主要用于记录地图初始化工作是否完成
- */
-
- import Accessor from "esri/core/Accessor";
- import { property, subclass } from "esri/core/accessorSupport/decorators";
-
- @subclass("custom.MO")
- class MO extends Accessor {
- private isOK: boolean = false;
-
- constructor() {
- super();
- this.isOK = false;
- }
-
- @property()
- get isIni(): boolean {
- return this.isOK;
- }
-
- set isIni(val: boolean) {
- const oldValue = this.get<boolean>("isIni");
- if (oldValue !== val) {
- // a setter has to update the value from the cache
- // this.set("isIni", val);
- this.isOK = val;
- this.notifyChange("isIni");
- }
- }
- }
-
- export = MO;
主函数中使用示例
- import watchUtils = require("esri/core/watchUtils");
-
-
- watchUtils.whenTrue(this.mo, "isIni", () => {
- if (tp == "layerlist") {
- if (collapsed) t.expandLayerList.collapse();
- else t.expandLayerList.expand();
- }
- if (tp == "legend") {
- if (collapsed) {
- t.expandLegend.collapse();
- } else {
- t.expandLegend.expand();
- }
- }
- });
需要注意避坑的是,在测试时出现异常:

一直怀疑是自定义类写的有问题,导致没有获取到该属性,查了很多资料,换了很多种写法。 最后忽然想起之前自己写的帖子,
ArcGIS JS TypeScript urlUtils使用问题_不超限的博客-CSDN博客
将import watchUtils from "" 的写法,更改为
import watchUtils = require("")
经过测试后,发现可以正常实现。
官方ArcGIS JS Accessor类
Implementing Accessor | Overview | ArcGIS API for JavaScript 4.24 | ArcGIS Developers