ToggleState

ToggleState

ToggleState represents a two value state with notification
mechanism when its state change.

The class can be imported with the following command:

import ToggleState from 'paraviewweb/src/Common/State/ToggleState';

constructor(initialState = true)

Return a ToggleState instance.

setState(value)

Update insternal state and trigger notification if the given
value is different than the current one.

getState(): boolean

Return the current state.

toggleState()

Toggle the current state which will trigger a notification.
That method is generated via a closure which allow it to be used
as a callback anywhere without any binding issue with
invalid this.

onChange(callback):subscription

Register a callback to any possible change of the model.
The callback method profile is as follow.

function(currentBooleanState, envelope){}

destroy()

Free memory and detatch any listener.

Source

index.js
import Monologue from 'monologue.js';

const CHANGE_TOPIC = 'toggle.change';

export default class ToggleState {
// ------------------------------------------------------------------------

constructor(initialState = true) {
this.state = initialState;

// Make a closure so that function can be passed around
this.toggleState = () => {
this.state = !this.state;
this.emit(CHANGE_TOPIC, this.state);
};
}

// ------------------------------------------------------------------------

setState(value) {
if (!!value !== this.state) {
this.state = !!value;
this.emit(CHANGE_TOPIC, this.state);
}
}

// ------------------------------------------------------------------------

getState() {
return this.state;
}

// ------------------------------------------------------------------------

onChange(callback) {
return this.on(CHANGE_TOPIC, callback);
}

// ------------------------------------------------------------------------

destroy() {
this.off();
}
}

// Add Observer pattern using Monologue.js
Monologue.mixInto(ToggleState);