diff --git a/index.js b/index.js index fe68426..24c8f14 100644 --- a/index.js +++ b/index.js @@ -51,6 +51,14 @@ this.actionHandlers[action] = [store]; } }, + unregister: function(action, store) { + console.log("unregister", action, store); + if (this.registeredFor(action).indexOf(store) === -1) return; + if (!this.actionHandlers.hasOwnProperty(action)) return; + this.actionHandlers[action] = this.actionHandlers[action].filter(function(registeredStore) { + return store !== registeredStore; + }); + }, dispatch: function(action) { var actionArgs = slice.call(arguments, 1); (this.actionHandlers[action] || []).forEach(function(store) { @@ -119,6 +127,20 @@ this.__listeners = this.__listeners.filter(function(registered) { return registered !== listener; }); + }, + registerAll: function() { + this.actions.forEach(function(Actions) { + Actions._registered.forEach(function(action) { + this._dispatcher.register(action, this); + }, this); + }, this); + }, + unregisterAll: function() { + this.actions.forEach(function(Actions) { + Actions._registered.forEach(function(action) { + this._dispatcher.unregister(action, this); + }, this); + }, this); } }; @@ -139,13 +161,8 @@ if (!Array.isArray(this.actions) || this.actions.length === 0) { throw new Error("Stores must define a non-empty actions array"); } - this.actions.forEach(function(Actions) { - // XXX check for valid Actions object - var dispatcher = Actions._dispatcher; - Actions._registered.forEach(function(action) { - dispatcher.register(action, this); - }, this); - }, this); + this._dispatcher = this.actions[0]._dispatcher; + this.registerAll(); } BaseStore.prototype = merge({ get state() { diff --git a/test.js b/test.js index d9daa56..cd053d9 100644 --- a/test.js +++ b/test.js @@ -468,6 +468,23 @@ describe("DocBrown.createStore()", function() { sinon.assert.calledOnce(listener); }); }); + + describe("#unregisterAll()", function() { + it("should unregister as action handler from the dispatcher", function() { + var Dispatcher = DocBrown.createDispatcher(); + var Actions = DocBrown.createActions(Dispatcher, ["a", "b"]); + var Store = DocBrown.createStore({actions: [Actions]}); + var store = new Store(); + + expect(Dispatcher.registeredFor("a")).to.include(store); + expect(Dispatcher.registeredFor("b")).to.include(store); + + store.unregisterAll(); + + expect(Dispatcher.registeredFor("a")).to.not.include(store); + expect(Dispatcher.registeredFor("b")).to.not.include(store); + }); + }); }); describe("DocBrown.storeMixin()", function() {