1 | function bindActionCreator(actionCreator, dispatch) {
|
2 | return (...args) => dispatch(actionCreator(...args))
|
3 | }
|
4 |
|
5 | /**
|
6 | * Turns an object whose values are action creators, into an object with the
|
7 | * same keys, but with every function wrapped into a `dispatch` call so they
|
8 | * may be invoked directly. This is just a convenience method, as you can call
|
9 | * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
|
10 | *
|
11 | * For convenience, you can also pass a single function as the first argument,
|
12 | * and get a function in return.
|
13 | *
|
14 | * @param {Function|Object} actionCreators An object whose values are action
|
15 | * creator functions. One handy way to obtain it is to use ES6 `import * as`
|
16 | * syntax. You may also pass a single function.
|
17 | *
|
18 | * @param {Function} dispatch The `dispatch` function available on your Redux
|
19 | * store.
|
20 | *
|
21 | * @returns {Function|Object} The object mimicking the original object, but with
|
22 | * every action creator wrapped into the `dispatch` call. If you passed a
|
23 | * function as `actionCreators`, the return value will also be a single
|
24 | * function.
|
25 | */
|
26 | export default function bindActionCreators(actionCreators, dispatch) {
|
27 | if (typeof actionCreators === 'function') {
|
28 | return bindActionCreator(actionCreators, dispatch)
|
29 | }
|
30 |
|
31 | if (typeof actionCreators !== 'object' || actionCreators === null) {
|
32 | throw new Error(
|
33 | `bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +
|
34 | `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
|
35 | )
|
36 | }
|
37 |
|
38 | var keys = Object.keys(actionCreators)
|
39 | var boundActionCreators = {}
|
40 | for (var i = 0; i < keys.length; i++) {
|
41 | var key = keys[i]
|
42 | var actionCreator = actionCreators[key]
|
43 | if (typeof actionCreator === 'function') {
|
44 | boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
|
45 | }
|
46 | }
|
47 | return boundActionCreators
|
48 | }
|