2014-09-29 05:57:51 -05:00
|
|
|
package eventer
|
|
|
|
|
2014-10-08 09:26:14 -05:00
|
|
|
import "sync"
|
|
|
|
|
2014-09-29 05:57:51 -05:00
|
|
|
// Basic receiver interface.
|
|
|
|
type Receiver interface {
|
|
|
|
Send(Event)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Receiver as channel
|
|
|
|
type Channel chan Event
|
|
|
|
|
|
|
|
func (self Channel) Send(ev Event) {
|
|
|
|
self <- ev
|
|
|
|
}
|
|
|
|
|
|
|
|
// Receiver as function
|
|
|
|
type Function func(ev Event)
|
|
|
|
|
|
|
|
func (self Function) Send(ev Event) {
|
|
|
|
self(ev)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Event struct {
|
|
|
|
Type string
|
|
|
|
Data interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Channels map[string][]Receiver
|
|
|
|
|
|
|
|
type EventMachine struct {
|
2014-10-08 09:26:14 -05:00
|
|
|
mu sync.RWMutex
|
2014-09-29 05:57:51 -05:00
|
|
|
channels Channels
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *EventMachine {
|
2014-10-08 09:26:14 -05:00
|
|
|
return &EventMachine{channels: make(Channels)}
|
2014-09-29 05:57:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self *EventMachine) add(typ string, r Receiver) {
|
2014-10-08 09:26:14 -05:00
|
|
|
self.mu.Lock()
|
2014-09-29 05:57:51 -05:00
|
|
|
self.channels[typ] = append(self.channels[typ], r)
|
2014-10-08 09:26:14 -05:00
|
|
|
self.mu.Unlock()
|
2014-09-29 05:57:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generalised methods for the known receiver types
|
|
|
|
// * Channel
|
|
|
|
// * Function
|
|
|
|
func (self *EventMachine) On(typ string, r interface{}) {
|
|
|
|
if eventFunc, ok := r.(func(Event)); ok {
|
|
|
|
self.RegisterFunc(typ, eventFunc)
|
|
|
|
} else if eventChan, ok := r.(Channel); ok {
|
|
|
|
self.RegisterChannel(typ, eventChan)
|
|
|
|
} else {
|
|
|
|
panic("Invalid type for EventMachine::On")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *EventMachine) RegisterChannel(typ string, c Channel) {
|
|
|
|
self.add(typ, c)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *EventMachine) RegisterFunc(typ string, f Function) {
|
|
|
|
self.add(typ, f)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *EventMachine) Register(typ string) Channel {
|
|
|
|
c := make(Channel, 1)
|
|
|
|
self.add(typ, c)
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *EventMachine) Post(typ string, data interface{}) {
|
2014-10-08 09:26:14 -05:00
|
|
|
self.mu.RLock()
|
2014-09-29 05:57:51 -05:00
|
|
|
if self.channels[typ] != nil {
|
|
|
|
ev := Event{typ, data}
|
|
|
|
for _, receiver := range self.channels[typ] {
|
|
|
|
// Blocking is OK. These are internals and need to be handled
|
|
|
|
receiver.Send(ev)
|
|
|
|
}
|
|
|
|
}
|
2014-10-08 09:26:14 -05:00
|
|
|
self.mu.RUnlock()
|
2014-09-29 05:57:51 -05:00
|
|
|
}
|