State management
Geogirafe uses a simple state manager based on Javascript Proxy objects, via the on-change library.
Any component that extends the <GirafeHTMLElement> class automatically inherits access to Geogirafe's state manager (via this.state). By convention, Geogirafe uses two locations to store a component's state variables:
this.statefor core components, e.g.this.state.themes,state.basemaps,state.mouseCoordinates, defined insrc/tools/state/state.ts.this.state.extendedStatefor custom/addon components, e.g.this.state.extendedState.helloworld, defined directly in custom components.
Observing changes on a state variable is done via the this.subscribe() method:
this.subscribe(
  "path to variable in state manager or regular expression",
  (_oldPropVal: any, _newPropVal: any, _parent: parentType) => {
    // callback function executed when a change on the observed variable is detected
  }
);
For example, to observe changes in the mouse coordinates variable in the core state (this.state.mouseCoordinates), we use:
this.subscribe(
  "mouseCoordinates",
  (_oldCoordinates: number[], _newCoordinates: number[]) => {
    console.log(_newCoordinates);
  }
);
The state manager is also able to detect deep changes in properties (i.e. multiple levels of nesting). If we wanted to monitor change only on a specific property of an an object in an array, you can use a regular expression with wildcards:
// Note that we use a regular expression with wildcards (*) here
this.subscribe(
  /extendedState\.helloworld\.markers\..*\.myproperty/,
  (_oldPropVal: boolean, _newPropVal: boolean, _parent: MyObjectType) => {
    // callback function executed when a change on the observed variable is detected
    console.log(
      `myproperty on parent object ${_parent.id} changed from ${_oldPropVal} to ${_newPropVal}`
    );
  }
);
To observe changes on the length of an array (i.e. e.g. when an item is added or deleted), you can use:
// Note that we use a string containing the path to the marker property here
this.stateManager.subscribe(
  "extendedState.helloworld.myarray",
  (
    _oldPropVal: MyObjectType[],
    _newPropVal: MyObjectType[],
    _parent: HelloState
  ) => {
    // callback function exectuted when a change on the observed variable is detected
  }
);