Class
Events
View sourceBuffers one typed event stream between writes and reads.
Events#write queues payloads in a pending buffer.
Events#clear publishes that buffer as the readable batch, which
Events#each, Events#readFirst, Events#readLast,
and Events#count inspect until the next clear. Writes after a clear
remain pending and are not part of the current readable batch.
Examples
import { Events } from '@wimaengine/event'
class Damage {
constructor(amount) {
this.amount = amount
}
}
const damageEvents = new Events()
damageEvents.write(new Damage(10))
damageEvents.write(new Damage(3))
damageEvents.clear()
damageEvents.each((event) => {
console.log(event.data.amount)
})
console.log(damageEvents.readFirst()?.data.amount) // 10
console.log(damageEvents.readLast()?.data.amount) // 3
console.log(damageEvents.count()) // 2
damageEvents.write(new Damage(1))
console.log(damageEvents.count()) // Still 2: the new write is pending.
damageEvents.clear()
console.log(damageEvents.count()) // 1Constructor
Methods
clear(): void
View sourcePublishes pending writes as the current readable batch.
The current write buffer becomes the read buffer, and a new empty write
buffer starts the next batch. The previous readable batch is replaced, but
its CEvent records are not mutated. Events written after this call
remain pending and are invisible to Events#each,
Events#readFirst, Events#readLast, and
Events#count until the next clear.
each(callback: EventReader<T>): void
View sourceCalls callback once for each event in the readable batch, in write order.
The callback receives a CEvent wrapper. Events queued by
Events#write while the callback runs are pending for the next
batch. The callback’s return value is ignored. An empty readable batch
produces no callback and the method returns undefined.
readFirst(): CEvent<T>
View sourceReturns the first event in the readable batch.
Returns the first CEvent in write order, or undefined when the
readable batch is empty. Read the typed payload from CEvent#data.
readLast(): CEvent<T>
View sourceReturns the last event in the readable batch.
Returns the last CEvent in write order, or undefined when the
readable batch is empty. Read the typed payload from CEvent#data.
write(data: T): void
View sourceQueues one typed payload for the next readable batch.
The method creates a CEvent record immediately, but read-side
methods cannot observe it until Events#clear rotates the write
buffer into the readable batch. The payload is not returned directly;
readers access it through CEvent#data.
count(): number
View sourceReturns the number of events in the current readable batch.
Payloads queued by Events#write after the last
Events#clear are not included. An empty readable batch
therefore has a count of 0, even if events are waiting in the write
buffer.
