From 614843bd2cc84a651229f89a0f0bc749a0249537 Mon Sep 17 00:00:00 2001 From: Josh Perez Date: Sun, 1 Feb 2015 12:00:40 -0800 Subject: [PATCH] Allow recycling of specific stores --- dist/alt.js | 21 ++++++++++++++++++++- src/alt.js | 21 +++++++++++++++++++-- test.js | 16 ++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/dist/alt.js b/dist/alt.js index c8e2fbcc..77e1248d 100644 --- a/dist/alt.js +++ b/dist/alt.js @@ -286,7 +286,26 @@ var Alt = (function () { }; Alt.prototype.recycle = function () { - bootstrap(this, this[INIT_SNAPSHOT]); + var storeNames = _slice.call(arguments); + + var snapshot = "{}"; + + if (storeNames.length) { + var stores = JSON.parse(this[INIT_SNAPSHOT]); + var storesToReset = storeNames.reduce(function (obj, name) { + if (!stores[name]) { + throw new ReferenceError("" + name + " is not a valid store"); + } + obj[name] = stores[name]; + return obj; + }, {}); + + snapshot = JSON.stringify(storesToReset); + } else { + snapshot = this[INIT_SNAPSHOT]; + } + + bootstrap(this, snapshot); }; Alt.prototype.flush = function () { diff --git a/src/alt.js b/src/alt.js index 0f23ec7d..a06144f8 100644 --- a/src/alt.js +++ b/src/alt.js @@ -282,8 +282,25 @@ your own custom identifier for each store` bootstrap(this, this[LAST_SNAPSHOT]) } - recycle() { - bootstrap(this, this[INIT_SNAPSHOT]) + recycle(...storeNames) { + var snapshot = '{}' + + if (storeNames.length) { + var stores = JSON.parse(this[INIT_SNAPSHOT]) + var storesToReset = storeNames.reduce((obj, name) => { + if (!stores[name]) { + throw new ReferenceError(`${name} is not a valid store`) + } + obj[name] = stores[name] + return obj + }, {}) + + snapshot = JSON.stringify(storesToReset) + } else { + snapshot = this[INIT_SNAPSHOT] + } + + bootstrap(this, snapshot) } flush() { diff --git a/test.js b/test.js index 6d7befd9..e1991e49 100644 --- a/test.js +++ b/test.js @@ -466,4 +466,20 @@ var lifecycleStore = alt.createStore(LifeCycleStore) var flushed = JSON.parse(alt.flush()) assert.equal(myStore.getState().name, 'first', 'flush is a lot like recycle') assert.equal(flushed.MyStore.name, 'goat', 'except that flush returns the state before recycling') + + myActions.updateName('butterfly') + assert.equal(myStore.getState().name, 'butterfly', 'I can update the state again after a flush') + assert.equal(secondStore.getState().name, 'butterfly', 'I can update the state again after a flush') + + alt.recycle('MyStore') + assert.equal(myStore.getState().name, 'first', 'I can recycle specific stores') + assert.equal(secondStore.getState().name, 'butterfly', 'and other stores will not be recycled') + + try { + alt.recycle('StoreThatDoesNotExist') + assert.equal(true, false, 'I was able to recycle a store that does not exist') + } catch (e) { + assert.equal(e instanceof ReferenceError, true, 'store that does not exist throws a RefenceError') + assert.equal(e.message, 'StoreThatDoesNotExist is not a valid store') + } }()