Skip to content

Commit

Permalink
Allow recycling of specific stores
Browse files Browse the repository at this point in the history
  • Loading branch information
goatslacker committed Feb 1, 2015
1 parent 4fd0b40 commit 614843b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 3 deletions.
21 changes: 20 additions & 1 deletion dist/alt.js
Expand Up @@ -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 () {
Expand Down
21 changes: 19 additions & 2 deletions src/alt.js
Expand Up @@ -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() {
Expand Down
16 changes: 16 additions & 0 deletions test.js
Expand Up @@ -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')
}
}()

0 comments on commit 614843b

Please sign in to comment.