Skip to content

Commit 81602c6

Browse files
committed
Gloobal action enhancers
1 parent 7d9730e commit 81602c6

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

src/store.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import applyMixin from './mixin'
22
import devtoolPlugin from './plugins/devtool'
33
import ModuleCollection from './module/module-collection'
4-
import { forEachValue, isObject, isPromise, assert } from './util'
4+
import { compose, forEachValue, isObject, isPromise, assert } from './util'
55

66
let Vue // bind on install
77

@@ -21,6 +21,7 @@ export class Store {
2121
}
2222

2323
const {
24+
actionEnhancers = [],
2425
plugins = [],
2526
strict = false
2627
} = options
@@ -42,9 +43,14 @@ export class Store {
4243
this._subscribers = []
4344
this._watcherVM = new Vue()
4445

45-
// bind commit and dispatch to self
4646
const store = this
47-
const { dispatch, commit } = this
47+
const { commit } = this
48+
let { dispatch } = this
49+
50+
const actionEnhancerChain = getActionEnhancerChain(store, state, actionEnhancers)
51+
dispatch = compose(...actionEnhancerChain)(dispatch.bind(store))
52+
53+
// bind commit and dispatch to self
4854
this.dispatch = function boundDispatch (type, payload) {
4955
return dispatch.call(store, type, payload)
5056
}
@@ -438,6 +444,15 @@ function enableStrictMode (store) {
438444
}, { deep: true, sync: true })
439445
}
440446

447+
function getActionEnhancerChain (store, state, actionEnhancers) {
448+
return actionEnhancers.map(actionEnhancer => actionEnhancer({
449+
dispatch: store.dispatch,
450+
commit: store.commit,
451+
getters: store.getters,
452+
state
453+
}))
454+
}
455+
441456
function getNestedState (state, path) {
442457
return path.length
443458
? path.reduce((state, key) => state[key], state)

src/util.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,26 @@ export function isPromise (val) {
6464
export function assert (condition, msg) {
6565
if (!condition) throw new Error(`[vuex] ${msg}`)
6666
}
67+
68+
/**
69+
* Taken from Redux repo
70+
* Composes single-argument functions from right to left. The rightmost
71+
* function can take multiple arguments as it provides the signature for
72+
* the resulting composite function.
73+
*
74+
* @param {...Function} funcs The functions to compose.
75+
* @returns {Function} A function obtained by composing the argument functions
76+
* from right to left. For example, compose(f, g, h) is identical to doing
77+
* (...args) => f(g(h(...args))).
78+
*/
79+
export function compose (...funcs) {
80+
if (funcs.length === 0) {
81+
return arg => arg
82+
}
83+
84+
if (funcs.length === 1) {
85+
return funcs[0]
86+
}
87+
88+
return funcs.reduce((a, b) => (...args) => a(b(...args)))
89+
}

0 commit comments

Comments
 (0)