Skip to content

Commit cb7f4fd

Browse files
committed
Merge pull request #939 from jzlxiaohei/master
fixed unsubscribe bug for issue #938
2 parents 1318f1c + 98b2e2f commit cb7f4fd

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/createStore.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export default function createStore(reducer, initialState) {
6262

6363
return function unsubscribe() {
6464
var index = listeners.indexOf(listener);
65-
listeners.splice(index, 1);
65+
if (index !== -1) {
66+
listeners.splice(index, 1);
67+
}
6668
};
6769
}
6870

test/createStore.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,23 @@ describe('createStore', () => {
201201
expect(listenerB.calls.length).toBe(2);
202202
});
203203

204+
it('should only remove relevant listener no matter how many times unsubscribe called', () => {
205+
const store = createStore(reducers.todos);
206+
const listenerA = expect.createSpy(() => {});
207+
const listenerB = expect.createSpy(() => {});
208+
209+
const unsubscribeA = store.subscribe(listenerA);
210+
store.subscribe(listenerB);
211+
212+
unsubscribeA();
213+
unsubscribeA();
214+
215+
store.dispatch(unknownAction());
216+
expect(listenerA.calls.length).toBe(0);
217+
expect(listenerB.calls.length).toBe(1);
218+
});
219+
220+
204221
it('should support removing a subscription within a subscription', () => {
205222
const store = createStore(reducers.todos);
206223
const listenerA = expect.createSpy(() => {});

0 commit comments

Comments
 (0)