While effects are how an app affects the outside world, subscriptions are how an app reacts to the outside world (e.g., listening to DOM events).
A subscriber is a function that:
- Receives
dispatch and options as arguments. - Sets up a listener (e.g.,
addEventListener). - Must return a cleanup function that tells Hyperapp how to stop listening (e.g.,
removeEventListener).
A subscription is a tuple in the format [subscriber, options].
Subscriptions are defined in the subscriptions property of the app configuration. This property accepts a function that receives the current state and returns an array of active subscriptions. Hyperapp automatically starts or stops subscriptions based on whether they are included in the returned array as the state changes.
Example of a keydown subscription:
const keydownSubscriber = (dispatch, options) => {
const handler = ev => {
if (ev.key !== options.key) return
dispatch(options.action)
}
addEventListener("keydown", handler)
return () => removeEventListener("keydown", handler)
}
const onKeyDown = (key, action) => [keydownSubscriber, {key, action}]
app({
...,
subscriptions: state => [
state.selected !== null &&
state.selected > 0 &&
onKeyDown("ArrowUp", SelectUp),
state.selected !== null &&
state.selected < (state.ids.length - 1) &&
onKeyDown("ArrowDown", SelectDown),
],
})
const keydownSubscriber = (dispatch, options) => {
const handler = ev => {
if (ev.key !== options.key) return
dispatch(options.action)
}
addEventListener("keydown", handler)
return () => removeEventListener("keydown", handler)
}
const onKeyDown = (key, action) => [keydownSubscriber, {key, action}]
app({
...,
subscriptions: state => [
state.selected !== null &&
state.selected > 0 &&
onKeyDown("ArrowUp", SelectUp),
state.selected !== null &&
state.selected < (state.ids.length - 1) &&
onKeyDown("ArrowDown", SelectDown),
],
})