# Code coverage report for lib/addons/fluxMixin.js

## Statements: 96.3% (78 / 81) Branches: 84.38% (27 / 32) Functions: 100% (18 / 18) Lines: 98.72% (77 / 78) Ignored: none

All files » lib/addons/ » fluxMixin.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216

    2

    1

    1
    1
    1

    1

    1
    7
    4

    7

    50

    27
    27
    27
    27
    27

    27

    1

    26

    2
    2

    2
    2

    2

    2

    24
    3

    3
    3

    49
    20

    45
    45
    45
    45
    19

    19

    19

    45
    8
    8
    8

    8

    8
    8

    8
    8
    37
    2
    2
    2

    2

    2

    2

    2
    4
    4
    4

    35
    7
    7

    7

    7

    7

    7
    7

    45

    1
    17
    14
    13
    13

    1
    15

    1
    3
    6

     "use strict";

    var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

    module.exports = fluxMixin;
    /**
     * fluxMixin
     *
     * Exports a function that creates a React component mixin. The mixin exposes
     * a Flux instance as `this.flux`. This requires that flux be passed as either
     * context or as a prop (prop takes precedence). Children also are given access
     * to flux instance as `context.flux`.
     *
     * It also adds the method `connectToStores()`, which ensures that the component
     * state stays in sync with the specified Flux stores. See the inline docs
     * of `connectToStores` for details.
     *
     * Any arguments passed to the mixin creator are passed to `connectToStores()`
     * and used as the return value of `getInitialState()`. This lets you handle
     * all of the state initialization and updates in a single place, while removing
     * the burden of manually adding and removing store listeners.
     *
     * @example
     * let Component = React.createClass({
     *   mixins: [fluxMixin({
     *     storeA: store => ({
     *       foo: store.state.a,
     *     }),
     *     storeB: store => ({
     *       bar: store.state.b,
     *     })
     *   }]
     * });
     */

    var PropTypes = require("react").PropTypes;
    var Flux = require("../Flux").Flux;
    var assign = _interopRequire(require("object-assign"));

    var shallowEqual = _interopRequire(require("react/lib/shallowEqual"));

    function fluxMixin() {
      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return {

        contextTypes: {
          flux: PropTypes.instanceOf(Flux) },

        childContextTypes: {
          flux: PropTypes.instanceOf(Flux) },

        getChildContext: function getChildContext() {
          return {
            flux: this.flux
          };
        },

        getInitialState: function getInitialState() {
          var _ref;
          this._fluxStateGetters = [];
          this._fluxListeners = {};
          this._fluxDidSyncStoreState = false;
          this.flux = this.props.flux || this.context.flux;

          if (!(this.flux instanceof Flux)) {
            // TODO: print the actual class name here
            throw new Error("fluxMixin: Could not find Flux instance. Ensure that your component " + "has either `this.context.flux` or `this.props.flux`.");
          }

          return (_ref = this).connectToStores.apply(_ref, args);
        },

        componentWillUnmount: function componentWillUnmount() {
          for (var key in this._fluxListeners) {
            Iif (!this._fluxListeners.hasOwnProperty(key)) continue;

            var store = this.flux.getStore(key);
            Iif (typeof store === "undefined") continue;

            var listener = this._fluxListeners[key];

            store.removeListener("change", listener);
          }
        },

        componentDidUpdate: function componentDidUpdate(prevProps) {
          if (!shallowEqual(prevProps, this.props)) {
            this.updateStores();
          }
        },

        updateStores: function updateStores() {
          var state = this.getStoreState();
          this.setState(state);
        },

        getStoreState: function getStoreState() {
          return this._fluxStateGetters.reduce(function (result, stateGetter) {
            return assign(result, stateGetter.getter(stateGetter.stores));
          }, {});
        },

        /**
         * Connect component to stores, get the combined initial state, and
         * subscribe to future changes. There are three ways to call it. The
         * simplest is to pass a single store key and, optionally, a state getter.
         * The state getter is a function that takes the store as a parameter and
         * returns the state that should be passed to the component's `setState()`.
         * If no state getter is specified, the default getter is used, which simply
         * returns the entire store state.
         *
         * The second form accepts an array of store keys. With this form, the state
         * getter is called once with an array of store instances (in the same order
         * as the store keys). the default getter performance a reduce on the entire
         * state for each store.
         *
         * The last form accepts an object of store keys mapped to state getters. As
         * a shortcut, you can pass `null` as a state getter to use the default
         * state getter.
         *
         * Returns the combined initial state of all specified stores.
         *
         * This way you can write all the initialization and update logic in a single
         * location, without having to mess with adding/removing listeners.
         *
         * @type {string|array|object} stateGetterMap - map of keys to getters
         * @returns {object} Combined initial state of stores
         */
        connectToStores: function connectToStores() {
          var _this = this;
          var stateGetterMap = arguments[0] === undefined ? {} : arguments[0];
          var stateGetter = arguments[1] === undefined ? null : arguments[1];
          var getStore = function (key) {
            var store = _this.flux.getStore(key);

            Iif (typeof store === "undefined") {
              throw new Error("connectToStores(): Store with key '" + key + "' does not exist.");
            }

            return store;
          };

          if (typeof stateGetterMap === "string") {
            var key = stateGetterMap;
            var store = getStore(key);
            var getter = stateGetter || defaultStateGetter;

            getter = getter.bind(this);

            this._fluxStateGetters.push({ stores: store, getter: getter });
            var listener = createStoreListener(this, store, getter).bind(this);

            store.addListener("change", listener);
            this._fluxListeners[key] = listener;
          } else if (Array.isArray(stateGetterMap)) {
            (function () {
              var stores = stateGetterMap.map(getStore);
              var getter = stateGetter || defaultReduceStateGetter;

              getter = getter.bind(_this);

              _this._fluxStateGetters.push({ stores: stores, getter: getter });

              var listener = createStoreListener(_this, stores, getter).bind(_this);

              stateGetterMap.forEach(function (key, index) {
                var store = stores[index];
                store.addListener("change", listener);
                _this._fluxListeners[key] = listener;
              });
            })();
          } else {
            for (var key in stateGetterMap) {
              var store = getStore(key);
              var getter = stateGetterMap[key] || defaultStateGetter;

              getter = getter.bind(this);

              this._fluxStateGetters.push({ stores: store, getter: getter });

              var listener = createStoreListener(this, store, getter).bind(this);

              store.addListener("change", listener);
              this._fluxListeners[key] = listener;
            }
          }

          return this.getStoreState();
        }

      };
    }

    function createStoreListener(component, store, storeStateGetter) {
      return function () {
        if (this.isMounted()) {
          var state = storeStateGetter(store);
          this.setState(state);
        }
      };
    }

    function defaultStateGetter(store) {
      return store.state;
    }

    function defaultReduceStateGetter(stores) {
      return stores.reduce(function (result, store) {
        return assign(result, store.state);
      }, {});
    }

    //# sourceMappingURL=data:application/json;base64,