diff --git a/README.md b/README.md index f4d4fd4..2306134 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ Creates a new store, which is a tiny evented state container. **Parameters** - `state` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Optional initial state (optional, default `{}`) +- `mutations` (optional, default `false`) **Examples** diff --git a/package.json b/package.json index 4345921..64e4cf6 100644 --- a/package.json +++ b/package.json @@ -28,11 +28,11 @@ "bundlesize": [ { "path": "full/preact.js", - "maxSize": "760b" + "maxSize": "819b" }, { "path": "dist/unistore.js", - "maxSize": "400b" + "maxSize": "417b" }, { "path": "preact.js", diff --git a/src/index.js b/src/index.js index 4df2006..ced5ece 100644 --- a/src/index.js +++ b/src/index.js @@ -11,7 +11,7 @@ import { assign } from './util'; * store.setState({ a: 'b' }); // logs { a: 'b' } * store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' } */ -export default function createStore(state) { +export default function createStore(state, mutations=false) { let listeners = []; state = state || {}; @@ -34,6 +34,11 @@ export default function createStore(state) { for (let i=0; i { expect(sub2).toBeCalledWith(store.getState(), action); }); + it('should invoke subscriptions using mutations', () => { + let store = createStore({ foo: 0 }, { + setFoo: (state, {v}) => ({ foo: v }), + }) + + let sub = jest.fn(); + let rval = store.subscribe(sub); + + store.mutate({ setFoo: { v: 1 } }); + expect(sub).toBeCalledWith(store.getState(), { setFoo: { v: 1 } }) + }); + it('should unsubscribe', () => { let store = createStore(); @@ -93,5 +105,14 @@ describe('createStore()', () => { expect(sub1).not.toBeCalled(); expect(sub2).not.toBeCalled(); expect(sub3).not.toBeCalled(); - }); + }); + + it('should allow mutations', () => { + let store = createStore({ foo: 0 }, { + setFoo: (state, {v}) => ({ foo: v }), + }) + + store.mutate({ setFoo: { v: 1 } }) + expect(store.getState()).toMatchObject({ foo: 1 }) + }); });