State API is a javascript interface for storing values and managing callbacks for changes to those values
npm install github:bemky/state
import State from 'state';const filter = new State({type: 'active'})
filter.addListener((filter, filterWas) => {
collection.where(filter)
})
filter.set({type: 'pending'})The root value of the state. The State uses value for valueOf, but in some cases you'll still need to use the actual value.
isOpen = new State(true)
if (isOpen == true) {} // works
if (isOpen.value) {} // works
if (isOpen) {} // does not workAlways true, helps frameworks identify a State.
if (typeof attribute == 'object' && attribute.isState) {}Removes and added callback
isOpen = new State(true)
isOpen.set(false)Add a callback to be run when value changes
addListener((oldValue, newValue, metadata) => {})Removes and added callback
function callback (oldValue, newValue, metadata) {}
addListener(callback)
removeListener(callback)Returns a new State that follows changes to this State, with the transformation applied to value everytime it changes
projectName = new State()
isSet = projectName.transform(v => v != null && v != undefined)
isSet.addListener(v => { console.log(isSet.value)})
projectName.set('New WIP')
// log: trueState works great with Dolla. This plugin modifies the setAttribute method to setup listeners when passing State values.
import { createElement } from 'dolla';
import 'state/plugins/dolla'
const bg = new State('white')
const el = createElement({
style: {
background: bg
}
})
bg.set('black')
el.style.background // >> blackThis plugin adds a state(attribute) method to Viking.Record.prototype. It returns a State that stays in sync with the record's attribute or association.
import { Record } from 'viking';
import 'state/plugins/viking'
class Ship extends Record {
static schema = {
name: { type: 'string' }
};
}
const ship = new Ship({ name: 'Black Pearl' })
const nameState = ship.state('name')
nameState.value // >> 'Black Pearl'
ship.name = 'Flying Dutchman'
nameState.value // >> 'Flying Dutchman'For associations, the State tracks the association's target:
const shipState = captain.state('ship')
shipState.value // >> Ship { name: 'Black Pearl' }- EJX
- Komps
