Documentation ¶
Overview ¶
Package event provides a reflect-based framework for low-frequency global dispatching of events, which are values of any arbitrary type, to a set of listener functions, which are usually registered by plugin packages during init().
Listeners should do work in a separate goroutine if it might block. Dispatch should be called synchronously to make sure work enters the listener's work queue before moving on. After Dispatch returns, the listener is responsible for arranging to flush its work queue before program termination if desired.
For example, any package can define an event type:
package mypackage type MyEvent struct { field1, field2 string }
Then, any other package (e.g. a plugin) can listen for those events:
package myplugin import ( "event" "mypackage" ) func onMyEvent(ev mypackage.MyEvent) { // do something with ev } func init() { event.AddListener(onMyEvent) }
Any registered listeners that accept a single argument of type MyEvent will be called when a value of type MyEvent is dispatched:
package myotherpackage import ( "event" "mypackage" ) func InMediasRes() { ev := mypackage.MyEvent{ field1: "foo", field2: "bar", } event.Dispatch(ev) }
In addition, listener functions that accept an interface type will be called for any dispatched value that implements the specified interface. A listener that accepts `any` will be called for every event type. Listeners can also accept pointer types, but they will only be called if the dispatch site calls Dispatch() on a pointer.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddListener ¶
func AddListener(fn any)
AddListener registers a listener function that will be called when a matching event is dispatched. The type of the function's first (and only) argument declares the event type (or interface) to listen for.
func Dispatch ¶
func Dispatch(ev any)
Dispatch sends an event to all registered listeners that were declared to accept values of the event's type, or interfaces that the value implements.
func DispatchUpdate ¶
DispatchUpdate calls Update() on the event and then dispatches it. This is a shortcut for combining updates and dispatches into a single call.
Types ¶
type BadListenerError ¶
type BadListenerError string
BadListenerError is raised via panic() when AddListener is called with an invalid listener function.
func (BadListenerError) Error ¶
func (why BadListenerError) Error() string