Simplest centralized state management for Riot.JS
A riot-state store consists of following properties: name
, state
, actions
. And provides following methods: dispatch
, install
Property name
is required if initial state would load from a global object.
By default riot-state
loads initial data from document.__GLOBAL_SHARED_STATE [name]
If there are more than one store it is possible to access them in an action
context by name.
const actions = {
ping(){
this.Stores.storeName.dispatch('pong')
}
}
A flat javascript object.
A javascript object containing functions. An action cannot be an arrow function
A component has to provide a list of shared
variables that will be injected in component scope.
export default {
shared: ['foo', 'bar']
}
//store.js
import { createStore } from "./state";
const name = "example";
const state = {
number: 0
};
const actions = {
increment(value = 1) {
this.number += value;
},
decrement(value = 1) {
this.number -= value;
}
};
export default createStore({
name,
state,
actions
});
<number>
<div class="number">
{number}
</div>
<script>
import store from './store'
export default ()=> ({
shared: [
'number'
],
onMounted(){
store.install(this)
this.update()
},
onUpdated(){
console.log(this.number)
}
})
</script>
</number>
<controls>
<button onclick={plus}>+</button>
<button onclick={minus}>-</button>
<script>
import store from './store'
export default () => ({
onMounted(){
store.install(this)
},
plus(){
store.dispatch('increment')
},
minus(){
store.dispatch('decrement')
},
})
</script>
</controls>
MIT