JSFiddle - React, Tailwind, and code Playground
by Adam Boduch
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/flux/2.1.1/Flux.js"></script>
JavaScript
// This dispatcher uses a Set instance to hold
// references to stores. When a payload is dispatched,
// we iterate over the stores, and call the action()
// method. If the store has any dependencies, we
// handle these stores first.
class Dispatcher {
constructor() {
this.stores = new Set();
}
register(store) {
this.stores.add(store);
// Alternatively, we could sort the stores as they're
// registered, based on their dependencies.
// stores.sort((a, b) => {
// if (a.deps.includes(b)) { return 1; }
// if (b.deps.includes(a)) { return -1; }
// return 0;
// })
}
unregister(store) {
this.stores.delete(store);
}
dispatch(payload) {
var seen = new Set();
for (let store of this.stores) {
for (let dep of store.deps) {
if (seen.has(dep)) {
continue;
}
seen.add(dep);
dep.action(payload);
}
if (seen.has(store)) {
continue;
}
seen.add(store);
store.action(payload);
}
}
}
const dispatcher = new Dispatcher();
class Store {
constructor(...deps) {
this.deps = deps;
dispatcher.register(this);
}
action(payload) {
console.log('payload', payload);
}
}
class MyStore extends Store {
constructor(deps) {
super(deps);
}
action(payload) {
console.log('my store', payload);
}
}
const store1 = new Store();
const store2 = new MyStore(store1);
dispatcher.dispatch('yo');