|
You can do what you want just in 17 lines of pure JavaScript. This is an example: const
create_store = ({state, actions}) => {
const
after_update_do = [],
subscribe = fn => after_update_do.push(fn),
notify = () => after_update_do.forEach(fn => fn(state)),
create_action = action => (...args) => {
state = action(state, ...args);
notify()
};
return Object.entries(actions).reduce((bound_actions, [action_name, action]) =>
Object.assign({}, bound_actions, {[action_name]: create_action(action)}),
{subscribe})
},
counter = create_store({
state: 0,
actions: {
increase: state => state + 1,
decrease: state => state - 1,
multiply_add: (state, a, b) => state * a + b,
},
});
counter.subscribe(state => console.log('First reactive component was updated with: ' + state));
counter.subscribe(state => console.log('Second reactive component was updated with: ' + state));
Now you can call all actions directly from the counter and update all components in reactive manner. counter.increase();
// First reactive component was updated with: 1
// Second reactive component was updated with: 1
counter.multiply_add(2, 3)
// First reactive component was updated with: 5
// Second reactive component was updated with: 5
|