Events, Listeners, schedules
An App declares an Event for each thing that happens in it and that other code reacts to. A handler publishes the Event, a Listener reacts to it, and a schedule publishes it by the clock.
Builder calls
Section titled “Builder calls”addEvent
Section titled “addEvent”template.addEvent(key: string): EventBuilderapp.addEvent(key: string): EventBuilderevent.input: InputBuilderevent.addChildEvent(event: EventBuilder): EventBuilderDeclares an Event of a Template or of the App. event.input declares its payload: the values a handler sends when it publishes the Event. Declare each one as a value of the input of an operation, with input.addProperty.
| Argument | Type | Description |
|---|---|---|
key |
string |
A lowercase letter, then letters and digits, 64 characters at most. A Template uses an Event key once, and so does an App. On a Template, created is taken. |
Returns the Event. The sample declares approved, with no payload, and rejected, with a note.
| Modifier | What it declares |
|---|---|
addChildEvent |
That a Listener of this Event publishes event. The Builder refuses Events that lead back to one another. Returns this Event. |
const approvedEvent = leaveRequest.addEvent('approved'); approvedEvent.addListener('announce', async (_event, item) => { console.log(`Listener: "${item.properties.reason}" is approved`); });
const rejectedEvent = leaveRequest.addEvent('rejected'); rejectedEvent.input.addProperty('note', 'string');Behavior
- An Event of a Template is published against one Item of that Template, and its Listeners get that Item.
- An Event of the App is published through
current, and its Listeners get the Workspace Item.
See: Events and current state, Handle events, Tutorial: what happens next, TemplateBuilder.addEvent.
addListener
Section titled “addListener”event.addListener( key: string, handler: EventListener,): EventListenerBuilderlistener( event: EventInstance, item: WriteItem, current: WriteAppInstance, ctx: WriteRuntimeInstance,): Promise<any>Declares a Listener: a function the Runtime runs each time the Event is published. The second signature is that function. event is the Event, item is the Item it was published against, and ctx is the context of a write execution. Where an App adds a Listener to an Event of its own, current is that App.
| Argument | Type | Description |
|---|---|---|
key |
string |
A key as for an Event. An Event uses a Listener key once. |
handler |
EventListener |
The function to run: the second signature above. |
Returns the Listener. The sample saves a notice on a request that was rejected.
rejectedEvent.addListener('notify', async (event, item) => { const note = event.payload.note; const notice = typeof note === 'string' ? `Rejected: ${note}` : 'Rejected'; await item.updateProperties({ notice }); });Behavior
- A Listener has not run when
publishreturns, nor when the Mutation that called it does. It runs when the queued work runs, and a later call reads what it wrote. - A Listener of an Event published with
publishruns as the system, not as the person whose call published it. It reads an Item that no Grant shows that person.
See: Listeners, parent Listeners and App Hooks, Handle events, Do something after a write commits, EventBuilder.addListener.
template.events
Section titled “template.events”template.events: TemplateEventsBuilderevents.created: EventBuilderThe Events of a Template, each under its key. An App that imports another App reads the Events of that App here, through the templates of what addDependency returns, and adds a Listener of its own to one.
created is an Event of every Template. No call to addEvent is needed for it.
In the sample plan runs when a shipment of the imported App arrives, and creates a project. greet runs for each new project.
const arrived = stock.templates.shipment.events.arrived; arrived.addListener('plan', async (_event, shipment, _current, ctx) => { const name = `Unpack ${shipment.properties.contents}`; await shipment.createChild(ctx.apps.work.templates.project, { properties: { name } }); });
const created = project.events.created; created.addListener('greet', async (_event, item, current) => { await current.events.digest.publish({ label: `New: ${item.properties.name}` }); });Behavior
- A Listener on an Event of an imported App runs when that Event is published.
- The Runtime publishes
created, with an empty payload, when a handler creates an Item of the Template. - The
eventsof an Item do not holdcreated, so a handler cannot publish it.
See: Events and current state, Employee onboarding checklists, TemplateBuilder.events.
addParentListener
Section titled “addParentListener”template.addParentListener( key: string, childEvent: EventBuilder, handler: EventParentListener,): EventParentListenerBuilderlistener( event: EventInstance, parent: WriteItem, child: WriteItem, current: WriteAppInstance, ctx: WriteRuntimeInstance,): Promise<any>Declares a Listener on a Template for an Event that is published against an Item below an Item of that Template. The second signature is its function: parent is the Item of the Template, and child is the Item the Event was published against.
| Argument | Type | Description |
|---|---|---|
key |
string |
A key as for an Event. A Template uses a parent Listener key once. |
childEvent |
EventBuilder |
The Event to listen to, as addEvent returns it. |
handler |
EventParentListener |
The function to run: the second signature above. |
Returns the Listener. In the sample a checklist counts the tasks that are finished below it.
const finished = task.addEvent('finished'); checklist.addParentListener('countDone', finished, async (_event, parent) => { const { done, total } = parent.properties; if (typeof done !== 'number') return; const updated = await parent.updateProperties({ done: done + 1 }); const transition = updated.state?.transitions.complete; if (done + 1 === total) await transition?.execute({}); });Behavior
- The Listener runs when the Event is published against a child of an Item of the Template, and gets that Item as
parent. - With a parent Listener on each of two Templates, the parent and the grandparent of the child both get the Event.
- It runs once for each Event: two Events published before one run of the queued work count two.
See: Listeners, parent Listeners and App Hooks, Roll a number up to a parent, Employee onboarding checklists, TemplateBuilder.addParentListener.
addSchedule
Section titled “addSchedule”event.addSchedule(key: string, crontab: string): EventSchedulerBuilderschedule.state(state: string | string[]): EventSchedulerBuilderDeclares a schedule: the Runtime publishes the Event by the clock, as a crontab sets it. It publishes an Event of a Template once for each Item the schedule covers, and an Event of the App once, against the Workspace Item.
| Argument | Type | Description |
|---|---|---|
key |
string |
A key as for an Event. An Event uses a schedule key once. |
crontab |
string |
Five fields: minute, hour, day of the month, month, day of the week. '0 9 * * 1-5' is 9:00, Monday to Friday. |
Returns the schedule.
| Modifier | What it declares |
|---|---|
state |
The states an Item is in to get the Event: one state key, or a list of them. Returns the schedule. |
const reminderDue = leaveRequest.addEvent('reminderDue'); reminderDue.addSchedule('weekdays', '0 9 * * 1-5').state(['pending']); reminderDue.addListener('remind', async (_event, item) => { await item.updateProperties({ notice: 'Waiting for a decision' }); });Behavior
- With
state, an Item in one of those states gets the Event, and no other Item does. - Without
state, an Item in any state gets the Event. - The Event is not published before a time of the crontab has passed. It is published at a run of the queued work once a time has passed since the run before.
- However many of those times have passed since the run before, the Event is published once.
- An Event of the App that a schedule publishes has an empty payload.
See: Events and current state, Handle events, Send a reminder when something sits too long, EventBuilder.addSchedule.
In a handler
Section titled “In a handler”publish
Section titled “publish”item.events: Record<string, WriteEventPublishInstance>current.events: Record<string, WriteEventPublishInstance>publisher.publish(payloadOrPayloads: any | any[]): Promise<void>Publishes an Event. item.events holds a publisher for each Event of the Template of the Item, by key, and current.events one for each Event of the App. The types give a Query neither.
| Argument | Type | Description |
|---|---|---|
payloadOrPayloads |
any | any[] |
The payload: an object with the values the Event declares, {} where it declares none. Or a list of payloads. |
Returns nothing. The sample publishes rejected with the note of the manager.
const reject = app.addMutation('reject', async (input: RejectInput, current) => { const item = await current.templates.leaveRequest.getItem(input.id); if (item === undefined || item.state?.value !== 'pending') { throw new Error('Leave request is not pending'); } const updated = await item.state.transitions.reject.execute({}); await updated.events.rejected.publish({ note: input.note }); return updated; });Behavior
- When the handler throws after
publish, no Event is saved and no Listener runs. - The Event is saved with the values its input declares. A key the input does not declare is left out.
publishthrows for a payload with no value for a mandatory key.- A list publishes one Event for each payload, and an empty list publishes none.
- A Listener publishes an Event the same way, and the Listeners of that Event run in turn.
See: Events and current state, Tutorial: what happens next, Do something after a write commits, WriteEventPublishInstance.publish.
event.payload
Section titled “event.payload”event.payload: PropertyMapevent.id: Identifierevent.createdAt: Dateevent.eventPrn: stringThe Event a Listener gets as its first argument, and a parent Listener too. payload holds the values the Event was published with, each under the key its input declares, as event.payload.note in the sample.
| Member | What it holds |
|---|---|
payload |
The values of the payload, by key. |
id |
The Identifier of the Event. |
createdAt |
The time the Event was published. |
eventPrn |
The PRN of the Event: prn::work:template/step/event/done for an Event of a Template, prn::work:app/event/digest for an Event of the App. |
The sample saves each of them on the step the Event was published against.
done.addListener('record', async (event, item) => { await item.updateProperties({ doneAt: event.createdAt.toISOString(), doneEvent: event.id, minutes: event.payload.minutes, note: event.payload.note, source: event.eventPrn, times: next(item.properties.times), }); });Behavior
createdAtis the time the Event was published, however much later the Listener runs.payloadhas no key for an optional value that was not sent.
See: Events and current state, Tutorial: what happens next, EventInstance.payload.
delay, cancel
Section titled “delay, cancel”publisher.delay(payload: any, delay: DurationLike): Promise<Identifier>publisher.cancel(id: Identifier): Promise<void>delay publishes an Event whose Listeners run once a length of time has passed. cancel takes a delayed Event back before they run. Each is a call on a publisher, as publish is.
| Argument | Type | Description |
|---|---|---|
payload |
any |
The payload, as for publish. |
delay |
DurationLike |
The length of time, in the form Luxon takes, as { hours: input.hours }. |
id |
Identifier |
The Identifier that delay returned. |
delay returns the Identifier of the delayed Event, and cancel returns nothing. In the sample remind saves the Identifier on the project, and cancels the reminder it set before.
const remind = app.addMutation('remind', async (input: RemindInput, current) => { const item = await current.templates.project.getItem(input.id); if (item === undefined) throw new Error('Project not found'); const { reminder } = item.properties; if (typeof reminder === 'string') await item.events.reminderDue.cancel(reminder); const later = await item.events.reminderDue.delay({}, { hours: input.hours }); return await item.updateProperties({ reminder: later }); });Behavior
- The Listeners of a delayed Event do not run before the delay has passed. They run when the queued work runs at that time or later.
- After
cancel, the Listeners of that Event do not run.
See: Events and current state, WriteEventPublishInstance.delay, WriteEventPublishInstance.cancel.

