From 7e7226213a380251021da36e458531fc73b782e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20K=C3=BChn?= Date: Mon, 15 Apr 2019 10:21:33 +0200 Subject: [PATCH] [IMP] store: commit a mutation in a mutation --- src/store.ts | 42 ++++++++++++++++++++++++++---------------- tests/store.test.ts | 19 +++++++++++++++++++ 2 files changed, 45 insertions(+), 16 deletions(-) diff --git a/src/store.ts b/src/store.ts index e95b0222..d139513d 100644 --- a/src/store.ts +++ b/src/store.ts @@ -21,6 +21,7 @@ export class Store extends EventBus { state: any; actions: any; mutations: any; + _commitLevel: number = 0; _isMutating: boolean = false; history: any[] = []; debug: boolean; @@ -64,35 +65,44 @@ export class Store extends EventBus { } } - async commit(type, payload?: any) { + commit(type, payload?: any) { if (!this.mutations[type]) { throw new Error(`[Error] mutation ${type} is undefined`); } + this._commitLevel++; const currentRev = this.observer.rev; - this._isMutating = true; this.observer.allowMutations = true; + this.mutations[type].call( null, - { state: this.state, set: this.observer.set }, + { + commit: this.commit.bind(this), + state: this.state, + set: this.observer.set + }, payload ); - this.observer.allowMutations = false; - if (this.debug) { - this.history.push({ - state: this.state, - mutation: type, - payload: payload + if (this._commitLevel === 1) { + this.observer.allowMutations = false; + if (this.debug) { + this.history.push({ + state: this.state, + mutation: type, + payload: payload + }); + } + Promise.resolve().then(() => { + if (this._isMutating) { + this._isMutating = false; + if (currentRev !== this.observer.rev) { + this.trigger("update", this.state); + } + } }); } - await Promise.resolve(); - if (this._isMutating) { - this._isMutating = false; - if (currentRev !== this.observer.rev) { - this.trigger("update", this.state); - } - } + this._commitLevel--; } } diff --git a/tests/store.test.ts b/tests/store.test.ts index 3c9929c3..18232af0 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -76,6 +76,25 @@ describe("basic use", () => { expect(store.state.n).toBe(101); }); + test("can commit a mutation in a mutation", () => { + const state = { n: 1 }; + const mutations = { + inc({ state }) { + state.n++; + }, + inc10({ commit }) { + for (let i = 0; i < 10; i++) { + commit("inc"); + } + } + }; + const store = new Store({ state, mutations }); + + expect(store.state.n).toBe(1); + store.commit("inc10"); + expect(store.state.n).toBe(11); + }); + test("dispatch allow synchronizing between actions", async () => { const state = { n: 1 }; const mutations = {