This module implements EventSource, which lets you register event handlers and then emit events.
Example:
import events var es = newEventSource[string]() messages: seq[string] count: int es.handle(msg): messages.add(msg) es.handle: inc(count) es.emit("foo") es.emit("bar") doAssert messages == @["foo", "bar"] doAssert count == 2
Types
EventSource[T] = object listeners: seq[proc (message: T): void]
Procs
proc `$`(ev: EventSource): string
proc `$`(ev: ref EventSource): string
proc addListener[T](es: var EventSource[T]; listener: proc (message: T): void)
- Add a proc to handle events. Proc will be called once for each event emit. See the handle template for a nicer syntax.
proc emit[T](es: EventSource[T]; message: T) {....gcsafe.}
- Emit an event to all event listeners
proc newEventSource[T](): EventSource[T]
proc removeListener[T](es: var EventSource[T]; listener: proc (message: T): void)
- Remove a proc from receiving any more events.
Templates
template handle[T](es: EventSource[T]; fnbody: untyped): untyped
-
Convient syntax for when you don't care about the event's message
Example:
var es = newEventSource[string]() es.handle: echo "Got a message" es.emit("some string")
template handle[T](es: EventSource[T]; varname: untyped; fnbody: untyped): untyped
-
Convient syntax for addListener
Example:
var es = newEventSource[string]() es.handle(thestring): echo "Got thestring: " & thestring es.emit("some string")