Skip to content

when

when<E>(test: (ev: E) => any, entryListener: EntryListener<E>): (ev: E) => void

Defined in: extras/when.ts:36

Creates a conditional entry/exit listener for an event.

When the test function returns true for an event, the entryListener is called and may return an exitListener. The exitListener (if returned) will be called on the next event before re-evaluating the test.

Usage:

when(
function testCondition(event) { return true },
function entryListener(event) {
// Handle condition entry logic
return functionExitListener(exitEvent) {
// Handle condition exit logic
};
}
)
Type ParameterDescription
EThe event type.
ParameterTypeDescription
test(ev: E) => anyFunction to test whether to trigger the entryListener.
entryListenerEntryListener<E>Function called when test passes; may return an exitListener.

A function to handle events, managing entry and exit listeners based on the test.

(ev: E): void

ParameterType
evE

void

const teardown = setup(machine)(
effect(whenFromState("Idle", fn)),
leave(whenState("Active", fn)),
enter(whenEventType("activate", fn))
);
// Call teardown() to remove listeners

Useful for composing conditional event listeners for state machines, enabling modular setup and teardown logic.

export function when<E>(test: (ev: E) => any, entryListener: EntryListener<E>) {
let exitListener: void | ((ev: E) => void);
return (ev: E) => {
if (exitListener) {
exitListener(ev);
exitListener = undefined;
}
if (test(ev)) {
exitListener = entryListener(ev);
}
};
}