Stores are used to manage the state of our APP. First we have to create a store with our initial state.
import { createStore } from 'dop'; const store = createStore({ red: 0, blue: 0 });
Then we subscribe to that store.
store.subscribe(patch => { console.log('patch', patch) // rerender component })
And finally we apply a patch and notify the listener.
const listeners = store.applyPatch({ red:1 }) listeners.forEach(({ listener, patch }) => listener(patch))
Unsubscribe
This is one way to unsubscribe.
const unsubscribe = store.subscribe(patch => {}) store.listeners.size // 1 unsubscribe() store.listeners.size // 0
This is the other way.
const listener = patch => {} store.subscribe(listener) store.listeners.size // 1 store.unsubscribe(listener) store.listeners.size // 0
Filtering
When subscribing, the second argument can be a function that filters what patches must be ignored.
const store = createStore({ users: 0 }) // Subscribing listener1 store.subscribe(listenerFunction1) // Subscribing listener2 with a filter store.subscribe(listenerFunction2, () => false) // Patching const listeners = store.applyPatch({ users: 1 }) listeners.length // 2 listeners[0].mutations.length // 1 listeners[0].patch // { users: 1 } listeners[0].unpatch // { users: 0 } listeners[1].mutations.length // 0 listeners[1].patch // { } listeners[1].unpatch // { }
If we don't pass filter, by default is a function that always returns true. ()=>true
Connecting nodes →