reflux / refluxjs

A simple library for uni-directional dataflow application architecture with React extensions inspired by Flux
BSD 3-Clause "New" or "Revised" License
5.36k stars 330 forks source link

Aggregate Store Pattern for Reflux #428

Closed souptown closed 8 years ago

souptown commented 9 years ago

This is not an issue. Just sharing a pattern.

Description: https://github.com/souptown/refluxjs-aggregate-store-pattern Example: http://codepen.io/anon/pen/xwPEMe

I'll copy it here:

refluxjs-aggregate-store-pattern

This is a pattern for creating aggregate stores in refluxjs.

var ParentStore = Reflux.createStore({

  init: function () {
    // Initial state
    this.state = {
      child: ChildStore.state
    };

    this.listenTo(ChildStore, this.onChildStoreEvent);
  },

  // Child stores changes
  onChildStoreEvent: function (newState) {
    this.state.child = newstate;
    this.trigger(this.state);
  }

});

var ChildStore = Reflux.createStore({
  listenables: ChildActions, // ChildActions.changeFoo is an action

  init: function () {
    this.state = {
      foo: ''
    };
  }

  onChangeFoo: function (newFoo) {
    this.state.foo = newFoo;
    this.trigger(this.state);
  }

});

Example

Shopping cart example

nidu commented 8 years ago

Why do you store a child reference in parent reference? Why not expose public API in ChildStore to access it's state? It would make dependencies more explicit i think.

souptown commented 8 years ago

I used this pattern to have a single state object for the page. https://github.com/souptown/react-refluxjs-single-page-state-pattern

By having the children as properties of the state, they are easily accessible to pass as props to child components in React.

devinivy commented 8 years ago

Interesting pattern– thanks for sharing! I've marked this as a "resource" so that people can find it in the issues. Any further conversation would fit perfectly into our new discussion repo (https://github.com/reflux/discuss), so don't hesitate to open a new issue over there!