Package events
is implementation of Observer
go.events
available through gopkg.in interface:
import "gopkg.in/adone/go.events.v2"
or directly from github:
import "github.com/adone/go.events.v2"
Create event:
event := events.New("eventName")
event.Context["key"] = value
Or create with predefined context:
data := events.Map{"foo": "bar"} // or map[string]interface{}{"foo": "bar"}
event := events.New("eventName", events.WithContext(data))
Emitter
can be embed into other struct:
type Object struct {
*events.Emitter
}
object := Object{events.NewEmitter()}
it is a preferable use of
Emitter
Emitter
supports different delivery strategies:
events.NewEmitter(events.WithDefaultStrategy(Broadcast))
events.NewEmitter(events.WithEventStrategy("event.for.parallel.processing", ParallelBroadcast))
You can define custom strategies by implementing DispatchStrategy
function:
customStrategy := func(event events.Event, listeners map[events.Listener]struct{}) {
// ...
}
em := events.NewEmitter()
em.Fire(events.New("event"))
fire event with parameters
em.Fire("event")
//or
em.Fire(events.New("event"))
- channels
channel := make(chan events.Event)
object.AddEventListener("event", events.Stream(channel))
- handlers
type Handler struct {}
func (Handler) Handle (events.Event) {
// handle events
}
object.AddEventListener("event", Handler{})
// or
object.On("event", Handler{}, Handler{}).On("anotherEvent", Handler{})
- functions
object.AddEventListener("event", events.Callback(func(event events.Event){
// handle event
}))
PeriodicEmitter
adds support for periodic events on Emitter
import (
"gopkg.in/adone/go.events.v2"
"time"
)
tick := events.NewTicker(events.NewEmitter())
tick.RegisterEvent("periodic.event.1", 5*time.Second)
// or
tick.RegisterEvent("periodic.event.2", time.NewTicker(5*time.Second))
// or
tick.RegisterEvent("periodic.event.3", 5*time.Second, Handler{})