Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Action before and after subscribers #1115

Merged
merged 5 commits into from
Jan 4, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,19 +128,28 @@ export class Store {
return
}

this._actionSubscribers.forEach(sub => sub(action, this.state))
this._actionSubscribers
.filter(sub => sub.before)
.forEach(sub => sub.before(action, this.state))

return entry.length > 1
const result = entry.length > 1
? Promise.all(entry.map(handler => handler(payload)))
: entry[0](payload)

result.then(() => this._actionSubscribers
.filter(sub => sub.after)
.forEach(sub => sub.after(action, this.state)))

return result
}

subscribe (fn) {
return genericSubscribe(fn, this._subscribers)
}

subscribeAction (fn) {
return genericSubscribe(fn, this._actionSubscribers)
const subs = typeof fn === 'function' ? { before: fn } : fn
return genericSubscribe(subs, this._actionSubscribers)
}

watch (getter, cb, options) {
Expand Down
31 changes: 31 additions & 0 deletions test/unit/modules.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,37 @@ describe('Modules', () => {
store.state
)
})

it('action before/after subscribers', (done) => {
const beforeSpy = jasmine.createSpy()
const afterSpy = jasmine.createSpy()
const store = new Vuex.Store({
actions: {
[TEST]: () => new Promise(resolve => resolve())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be simplified with Promise.resolve() 🙂

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh duh. Will update!

},
plugins: [
store => {
store.subscribeAction({
before: beforeSpy,
after: afterSpy
})
}
]
})
store.dispatch(TEST, 2)
expect(beforeSpy).toHaveBeenCalledWith(
{ type: TEST, payload: 2 },
store.state
)
expect(afterSpy).not.toHaveBeenCalled()
Vue.nextTick(() => {
expect(afterSpy).toHaveBeenCalledWith(
{ type: TEST, payload: 2 },
store.state
)
done()
})
})
})

it('asserts a mutation should be a function', () => {
Expand Down