Skip to content

5.1 State

amaliejvik edited this page Aug 5, 2024 · 1 revision

State is a generic class, and a State object can be initialized and added to LegendBox through its constructor or with its .addElement()-method. State uses an event emitter to notify observers about state changes.

Parameters:

Required:

  • stateName: string The name of the state (Ex: "a")
  • initialState: T The initial value of the State (Ex:10)

Optional:

  • inLegend?: boolean Whether or not to display the state on its own line in LegendBox

Default Parameters:

  inLegend: true

Methods

  • addObserver(callback:(state: T): Adds an observer to the current State, and registers a function that will be called whenever a specific state change event occurs
  • removeObserver(callback:(state: T): Removes an observer from the current State

Examples

Example 1: Initialization of States

image
  1. With inLegend optional set: const state1 = new State("a", 5, { inLegend: false });

  2. Without inLegend optional: const state2 = new State("b", 100);

NOTE: b will be displayed in LegendBox since inLegend defaults to true


Example 2: Add States to LegendBox

Skjermbilde 2024-08-05 kl  16 02 27

There are two ways to add states to the LegendBox similar to how all other elements are added:

  1. In the constructor: const legend = new LegendBox([state1, plot1, text1]);
  2. With .addElement(): legend.addElement(state2);

Example 3: Get LegendText objects to depend on states

LegendText has a boolean option called "useStates" which defaults to false. If useStates is set to true in the constructor on a LegendText object, it will be added as an observer to the declared states it contains.

As text:

// 1. Create a LegendText object which uses states
const text2 = new LegendText("\\int_{a}^{b} x^2\\,dx", {
  color: "#faa307", 
  shape: "circle", 
  useStates: true,
});

// 2. Create two State objects "a" and "b"
const state1 = new State("a", 5, { inLegend: false });
const state2 = new State("b", 100); 

// 3. Add states and LegendText to LegendBox
//NOTE: text2 will now listen to state1 and state2, since it contains "a" and "b" and since useStates is true
const legend = new LegendBox([state1, plot1, text2, state2]);

// 4. Run core with State-changes
const core = new Core();
core.run((t) => {
    state1.setState(state1.getState() + t / 100);
    state2.setState(state2.getState() + t / 100);
});

As a photo:

Skjermbilde 2024-08-05 kl  16 13 28