3 ms·
Just because a framework/language gives you a tool, doesn't mean you need to use it. Instead of emit, you can easily track state in a Vuex store and then have t
by fny 8y ago
Just because a framework/language gives you a tool, doesn't mean you need to use it. Instead of emit, you can easily track state in a Vuex store and then have that change propagate to the required components.
- wolco 8y agoA store could be used and things get cleaner but the overhead increases too much.
- anonytrary 8y agoYou can also inject sideways data dependencies in React by using an event emitter. Shitty POC: // global-store.js const remove = (arr, el) => { const i = arr.indexOf(el); if (i < 0) return false; return !!arr.splice(i, 1); } class GlobalStore { constructor(data){ this.data = data; this.subs = []; } sub(cb){this.subs.push(cb)} unsub(cb){remove(this.subs, cb)} notify(newArr){ for (let s of this.subs) s(newArr); } addData(item){ notify(this.data = [...data, item]) } removeData(item){ if (remove(this.data, item)) notify(this.data = [...this.data]) } } // my-component.js import myStore from "./stores" class MyComp extends Component { ... componentDidMount(){ myStore.sub(this._cb = data => { this.setState({data}) }) } componentWillUnmount(){ myStore.unsub(this._cb) } } Obviously, not super optimized, but it's just a POC.