diff --git a/fluctuations.js b/fluctuations.js index 6a2a655..dc8006b 100644 --- a/fluctuations.js +++ b/fluctuations.js @@ -15,16 +15,6 @@ function createDispatcher(options) { var interceptors = {}; var listeners = {}; - return { - addInterceptor: addInterceptor, - addStore: addStore, - - dispatch: dispatch, - - listen: listen, - get: get - }; - function addInterceptor(key, interceptor) { interceptors[key] = interceptor; } @@ -48,6 +38,7 @@ function createDispatcher(options) { function dispatchToInterceptors(action, payload) { debug("Dispatching %s to interceptors", action); var intercepted = false; + dispatchToStores.state = get(); each(interceptors, function(interceptor, key) { if (interceptor.handlers[action]) { debug("Intercepted %s with interceptor '%s'", action, key); @@ -79,6 +70,8 @@ function createDispatcher(options) { console.warn("Unknown action: %s", action, payload); } } + dispatchToStores.dispatch = dispatchToStores; + dispatchToStores.state = get(); function notify() { debug('Notifying all listeners'); @@ -91,6 +84,16 @@ function createDispatcher(options) { return state; } + return { + addInterceptor: addInterceptor, + addStore: addStore, + + dispatch: dispatch, + + listen: listen, + get: get + }; + } function createStore(initial, handlers, merge) { diff --git a/test/test.js b/test/test.js index e86bc26..2ecf345 100644 --- a/test/test.js +++ b/test/test.js @@ -196,6 +196,7 @@ describe("fluctuations", function() { { QUICK_INC: function(n) { return n + 1; }, INC: storeInc, + SUB: function(n, i) { return n - i; }, START_INC: function(n) { return n + 0.1; }, END_INC: function(n) { return n + 0.9; } } @@ -204,6 +205,18 @@ describe("fluctuations", function() { INC: function(dispatch) { dispatch("START_INC"); }, + ADD: function(dispatch, n) { + while (n--) dispatch("INC"); + }, + SUB5: function(dispatch) { + dispatch("SUB", 5); + }, + AT_LEAST: function(dispatcher, n) { + if (n > dispatcher.state.n) { + var i = n - dispatcher.state.n; + while (i--) dispatcher.dispatch("INC"); + } + }, HIJACK: function(dispatch) { interceptions.push(dispatch); } @@ -248,8 +261,26 @@ describe("fluctuations", function() { }); }); - it("should receive payloads in interceptors"); - it("should allow interceptors to dispatch payloads to stores"); + it("should receive payloads in interceptors", function() { + flux.dispatch("ADD", 5); + expect(flux.get().n).to.eql(5); + expect(storeInc).to.have.callCount(5); + }); + + it("should allow interceptors to dispatch payloads to stores", function() { + flux.dispatch("SUB5"); + expect(flux.get().n).to.eql(-5); + }); + + it("should allow interceptors to read state", function() { + flux.dispatch("AT_LEAST", 3); + expect(flux.get().n).to.eql(3); + expect(storeInc).to.have.callCount(3); + flux.dispatch("SUB5"); + flux.dispatch("AT_LEAST", 3); + expect(flux.get().n).to.eql(3); + expect(storeInc).to.have.callCount(8); + }); }); describe("multiple overlapping interceptors", function() {