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