cap:restorable-state
- capture and restore state¶
restorable-state
provides an extension to state that supports
capturing and setting state.
if(thing.matches('cap:restorable-state')) {
console.log('Keys that can be restored:' , thing.restorableState);
// Capture the state
const state = await thing.captureState();
// A bit later the state can be restored
await thing.setState(state);
}
API¶
-
restorableState
¶ Get an array of the state-keys that are restorable.
Example:
console.log(thing.restorableState); console.log(thing.restorableState[0]);
-
captureState
()¶ Capture all the state that can be restored.
Returns: Promise that resolves to the object representing the state. Example:
thing.setState(state) .then(...) .catch(...); const state = await thing.captureState();
-
setState
(state)¶ Set the state of the thing. Can be used together with result captured via
captureState()
.Arguments: - state (object) – State to set.
Returns: Promise that will resolve when state has been set.
Example:
thing.setState(state) .then(...) .catch(...); await thing.setState(state);
Protected methods¶
-
changeState
(state)¶ Abstract. Change the state of the thing. Implementations should call
super
and restore custom state-keys when that promise resolves.Example:
changeState(state) { return super.changeState(state) .then(() => { if(typeof state.color !== 'undefined') { return changeColorSomehow(state.color); } }); }
Implementing capability¶
Most implementations of this capability are by other capabilities.
Implementations need to override both get restorableState
and
changeState
.
The getter for restorableState
must also take care to include the state-keys
defined as restorable by its parent:
get restorableState() {
return [ ...super.restorableState, 'own-key' ];
}
It is recommended to provide a method that defines a default restore behavior, so that its easy to override the default behavior if needed.
Example:
const { Thing, RestorableState } = require('abstract-things');
const Custom = Thing.capability(Parent => class extends Parent.with(RestorableState) {
get restorableState() {
// Must call super.restorableState and make it part of the result
return [ ...super.restorableState, 'color' ];
}
changeState(state) {
return super.changeState(state)
.then(() => {
if(typeof state.color !== 'undefined') {
return this.setColorState(state.color);
}
});
}
setColorState(color) {
// The default restore behavior is to call setColor
return this.setColor(color);
}
setColor(color) {
...
}
});