Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
37 changes: 36 additions & 1 deletion src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default function createStore(reducer, initialState) {
var currentState = initialState;
var listeners = [];
var isDispatching = false;
var inTransaction = false;

/**
* Reads the state tree managed by the store.
Expand Down Expand Up @@ -117,10 +118,42 @@ export default function createStore(reducer, initialState) {
isDispatching = false;
}

listeners.slice().forEach(listener => listener());
if (!inTransaction) {
listeners.slice().forEach(listener => listener());
}
return action;
}

/**
* Start transaction
*
* No one listeners will be called until commit() transaction.
*
* @return {void}
*/
function begin() {
if (inTransaction) {
throw new Error(
'Only one transaction may be started with begin() call.'
);
}
inTransaction = true;
}

/**
* Commit
* @return {void}
*/
function commit() {
if (!inTransaction) {
throw new Error(
'You must call begin() before commit().'
);
}
inTransaction = false;
listeners.slice().forEach(listener => listener());
}

/**
* Replaces the reducer currently used by the store to calculate the state.
*
Expand All @@ -142,6 +175,8 @@ export default function createStore(reducer, initialState) {
dispatch({ type: ActionTypes.INIT });

return {
begin,
commit,
dispatch,
subscribe,
getState,
Expand Down
23 changes: 22 additions & 1 deletion test/createStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ describe('createStore', () => {
const store = createStore(combineReducers(reducers));
const methods = Object.keys(store);

expect(methods.length).toBe(4);
expect(methods.length).toBe(6);
expect(methods).toContain('subscribe');
expect(methods).toContain('dispatch');
expect(methods).toContain('getState');
expect(methods).toContain('replaceReducer');
expect(methods).toContain('begin');
expect(methods).toContain('commit');
});

it('should require a reducer function', () => {
Expand Down Expand Up @@ -321,4 +323,23 @@ describe('createStore', () => {
store.dispatch({ type: '' })
).toNotThrow();
});

it('should not call listeners if begin() called', () => {
const store = createStore(reducers.todos);
let called = false;
store.subscribe(() => {
called = true;
});

store.dispatch({type: 'test'});
expect(called).toBe(true);
called = false;

store.begin();
store.dispatch({type: 'test'});
expect(called).toBe(false);

store.commit();
expect(called).toBe(true);
});
});