Skip to content

Commit

Permalink
Handle effects returned from event handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
stwa committed Jun 7, 2019
1 parent c038ee9 commit 433be44
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/event.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { queue } from "./internal/queue";
import { effect } from "./effect";

/**
* The event module provides machanisms to trigger and handle the happening of
Expand Down Expand Up @@ -28,7 +29,7 @@ export const eventQueue = queue();
* and must return a map of effects that should be applied.
*/
export function handling(eventId, handlerFn) {
return rawHandling(eventId, [], context => {
return rawHandling(eventId, [effectsInterceptor], context => {
let [eventId, args] = context.causes.event;
context.effects = handlerFn(context.causes, eventId, ...args);
return context;
Expand Down Expand Up @@ -97,6 +98,20 @@ export function clearHandlings() {
registry.clear();
}

/**
* An interceptor which calls the corresponding effect handler for each
* described effect in `context.effects`.
*/
export function effectsInterceptor(nextFn) {
return context => {
context = nextFn(context);
for (let effectId in context.effects) {
effect(effectId, context.effects[effectId]);
}
return context;
};
}

function handle(eventId, ...args) {
let handlerFn = registry.get(eventId);
if (handlerFn) {
Expand Down
13 changes: 13 additions & 0 deletions src/event.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
handling,
rawHandling,
} from "./event";
import { clearEffectors, effector } from "./effect";

/* global global */

Expand Down Expand Up @@ -36,6 +37,7 @@ beforeEach(() => {
global.console.warn = jest.fn();
eventQueue.tickFn(ticker.dispatch);
clearHandlings();
clearEffectors();
});

describe("handling", () => {
Expand All @@ -51,6 +53,17 @@ describe("handling", () => {
expect(context.causes.event).toStrictEqual(["foo", ["bar", "baz"]]);
expect(context.effects.succeed).toBeTruthy();
});
it("handles effects from context", () => {
let succeed = false;
let handler = handling("foo", () => ({ bar: "baz" }));
effector("bar", arg => {
expect(arg).toBe("baz");
succeed = true;
});
expect(succeed).toBeFalsy();
handler("foo");
expect(succeed).toBeTruthy();
});
});

describe("rawHandling", () => {
Expand Down

0 comments on commit 433be44

Please sign in to comment.