storx
TypeScript icon, indicating that this package has built-in type declarations

0.1.9 • Public • Published

Build Status codecov Dependency Status npm npm

Basic Usage

  1. Create a store and bind a reducer to event
let store = StoRx.createStore({ name : 'stoRx', counter : 0 });
store.action().subscribe((state, action)=> { let newState = ...state;
            newState.name = action.name; newState.count++; return newState; } );
  1. To get the state update we subscribe to the state Observable
store.observable().subscribe(state=>console.log(state));
  1. We trigger an event
store.dispatch({ name : 'newname'});

Using Substore

with the previous example it's just look like a lame redux / rxjs, so we gonna deep further with the same example but using map and filter

  1. Create a store and a substore pointing to the name and one to the counter
let store = StoRx.createStore({ name : 'stoRx', counter : 0 });
let nameStore = store.map('name');
let countStore = store.map('counter');

// here the subscribe is done on a store that has for state directly the name
// so we just for reducer return the new name
// of course we filter out action that do not provide a new name
nameStore.action().filter(action=>action.name!==null).subscribe((state,action)=> action.name);

// he we just want to count all the action
// the state contains directly the count value
countStore.action().subscribe((state,action)=> state+1);
  1. To get the state update we subscribe to the state Observable
store.observable().subscribe(state=>console.log(state));
// be we can also subscribe to the substore
nameStore.observable().subscribe(nameState=>console.log('nameStore', nameState));
countStore.observable().subscribe(countState=>console.log('countStore', countState));
  1. We trigger an event
store.dispatch({ name : null});
store.dispatch({ name : 'newname'});

Binding directly to event

we can use the dispatch like redux, but we can also directly bind to any javascript event

let el = document.getElementById('MyButton');
countStore.subscribe(Observable.fromEvent(el,'click'), (state,actionEvent)=>state+1);

we can have reducer on any Observable.

To Sum it up !

  • with the sub store we can modularized and even simplify our reducer ( they can directly return the name ).
  • we avoid big switch on action type with filters to decide what to do with the event.
  • we can even reuse reducer on multiple substore.
  • we can take advantage of the Observable transformation function to bind Recuder with the Store.subscribeReducer(observable, reducer)

TODOS

  • Add time machine feature

License

The MIT License (MIT) - See file 'LICENSE' in this project

Copyright

Copyright © 2017 Benoît Roger. All Rights Reserved.

Readme

Keywords

none

Package Sidebar

Install

npm i storx

Weekly Downloads

2

Version

0.1.9

License

MIT

Last publish

Collaborators

  • binig