Skip to content

Basic usage

Rich Harris edited this page Jan 6, 2013 · 7 revisions

WikiBasic usage

Include Statesman.js on your page. Then,

var state = new Statesman( data );

Initialising with data is optional (see Creating new branches below). Once your state model is setup, you can set and get data like so:

state.set( 'foo', 'bar' );
state.get( 'foo' ); // returns 'bar'

Nested values

Unless your app is extremely simple it's likely that your state model will have nested values, which is to say that some properties will be objects or arrays:

var state = new Statesman({
    browser: {
        supports: {
            someFeature: testFor( 'someFeature' ),
            anotherFeature: testFor( 'anotherFeature' )
        }
    },
    user: {
        id: 123456,
        name: 'Winston Churchill',
        email: 'winston@statesmenRus.com',
        friends: [
            'Franklin',
            'Joseph',
            'Charles',
            'Harry'
        ]
    }
});

You can set and get these nested values using the familiar JavaScript syntax:

state.get( 'user.friends[0]' ); // returns 'Franklin'

(This is in fact equivalent to 'user.friends.0', if you're so inclined.)

Note that normally in JavaScript, if you tried to retrieve the value of user.friends[0] you would get an error if user or user.friends hadn't been defined yet, hence this common pattern:

if ( user && user.friends ) {
    doSomethingWith( user.friends[0] );
}

In Statesman.js, no error will be thrown if the upstream keypaths (user and user.friends) don't exist - it will just return undefined.

Similarly, if you did state.set( 'user.friends[0]', 'Franklin' ) and there was no such thing as user or user.friends, Statesman.js would create those branches, and would recognise that user.friends was meant to be an array rather than an object.

Setting multiple keypaths in one go

The following are basically equivalent:

state.set( 'foo', 'bar' );
state.set( 'bar', 'baz' );
state.set( 'user.id', 123456 );

and

state.set({
    foo: 'bar',
    bar: 'baz'
    'user.id': 123456
});

I say basically equivalent, but they're not exactly equivalent. If you set multiple values that share an observer in one go, the observer will only be notified once.

Next: observers

Something went wrong with that request. Please try again.