Skip to content

bemky/state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

State

State API is a javascript interface for storing values and managing callbacks for changes to those values

Installation

npm install github:bemky/state
import State from 'state';

Example

const filter = new State({type: 'active'})
filter.addListener((filter, filterWas) => {
    collection.where(filter)
})

filter.set({type: 'pending'})

Properties

value

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 work

isState

Always true, helps frameworks identify a State.

if (typeof attribute == 'object' && attribute.isState) {}

Methods

set(value)

Removes and added callback

isOpen = new State(true)
isOpen.set(false)

addListener(callback:function)

Add a callback to be run when value changes

addListener((oldValue, newValue, metadata) => {})

removeListener(callback:function)

Removes and added callback

function callback (oldValue, newValue, metadata) {} 
addListener(callback)
removeListener(callback)

transform(transformation:function)

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: true

Plugins

State 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 // >> black

This 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' }

TODO

  • EJX
  • Komps

About

A javascript API for binding callbacks to values

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors