JavaScript data structures with immutable state events.
Install
Then:
const pek = require ( 'pek' );
copy
Quick Start
To get started, create a data model for your application using the same data
types as you would with JSON (String, Number, Boolean, Object, Array, and null):
const APP_STATE = {
name: 'Todo List' ,
lists: [
{name: 'Shopping' , items: [ 'Milk' , 'Bananas' ]},
]
};
copy
Next, create a Pēk model by passing this data model to pek():
const model = pek (APP_STATE); // ⇨ { name: 'Todo List', lists: [ { name: 'Shopping', items: [Object] } ] }
copy
That's pretty much all there is to it. Your Pēk model looks and feels just like the original:
model.lists[ 0 ].name = 'Zoo Supplies' ;
model.lists[ 0 ].items. push ( 'Monkeys' );
model.lists[ 0 ]; // ⇨ { name: 'Zoo Supplies', items: [ 'Milk', 'Bananas', 'Monkeys' ] }
copy
... with one important difference - you can subscribe to state changes :
const unsubscribe = model.__. on (state => console. log (state));
model.name = 'Pek Example' ; copy
Anytime your Pēk model changes, all listeners are notified. Moreover, the state listeners receive is immutable:
model.__. on (state => {
state.name = 'Nopity nope nope' ;
state.name; // ⇨ 'Pek Example 2'
});
model.name = ' \P ek Example 2' ;
copy
In non-strict mode, changing the state will fail silently, as above. In strict
mode, changing the state will throw an exception:
model.__. on (state => {
'use strict' ;
try {
state.name = 'Nopity nope nope' ;
} catch (err) {
console. log (err.message);
}
});
model.name = ' \P ek Example 3' ;
⇒ Cannot assign to read only property 'name' of object '[object Object]' copy
API
pek(initialState)
Creates a new Pēk model
initialState - Object or Array holding your initial model state
Returns a Pēk model (a Proxy-wrapped version of initialState)
E.g.
const model = pek ({a: 'hello' , b: [ 'world' ]}); // ⇨ { a: 'hello', b: [ 'world' ] }
copy
model. ... __.on(callback)
Listen for changes to model state.
callback - Function to call any time the target object or any of it's
subordinate objects change state. This function takes the following arguments:
state - An immutable copy of the object state. Attempting to modify
Returns unsubscriber Function.
const unsubscribe = model.__. on (immutableState => console. log (immutableState));
model.a = 'Hello' ;
⇒ { a : 'Hello' , b : [ 'world' ] } copy
To unsubscribe, call the returned unsubscriber Function:
Markdown generated from src/README_js.md by