-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Stores | ||
|
||
The responsibility of a Store in Microcosm is to transform state from | ||
one form to the next. They do not provide any storage of their own | ||
(although technically this isn't enforced by Microcosm). | ||
|
||
Stores boil down to: | ||
|
||
```javascript | ||
var store = { | ||
getInitialState() { | ||
// return a starting value | ||
}, | ||
serialize(state) { | ||
// transform data when app.toJSON() is called | ||
}, | ||
deserialize(state) { | ||
// parse data when app.seed is called | ||
}, | ||
toString() { | ||
// return a unique identifier | ||
} | ||
} | ||
``` | ||
|
||
Of these methods, only the `toString` method is required. If this | ||
method is not implemented Microcosm will quickly throw an error: | ||
|
||
``` | ||
Stores must implement a toString() method | ||
``` | ||
|
||
## Installing Stores | ||
|
||
Microcosms must add stores: | ||
|
||
```javascript | ||
let app = new Microcosm() | ||
|
||
let MyStore = { | ||
toString() { | ||
return 'mystore' | ||
} | ||
} | ||
|
||
app.addStore(MyStore) | ||
``` | ||
|
||
This will mix the given store on top of a set of defaults (see | ||
`src/Store.js`) and run `getInitialState()` if it is | ||
provided. Additionally, the Micocosm instance will now be configured | ||
to use `MyStore` to manage state under the `mystore` key (because of | ||
the `toString` method). | ||
|
||
This state can be accessed like: | ||
|
||
```javascript | ||
app.get(MyStore) | ||
``` | ||
|
||
## Listening to Actions | ||
|
||
Stores listen to actions by implement them as methods: | ||
|
||
```javascript | ||
let MyStore = { | ||
[Action.add](state, record) { | ||
return state.concat(record) | ||
}, | ||
toString() { | ||
return 'my-store' | ||
} | ||
} | ||
``` | ||
|
||
The first argument of this method will always be the application state | ||
for the given key provided by `toString()`. It is the responsibility | ||
of the store to return the next state as a result of actions. |