Add events
This commit is contained in:
16
event/event.go
Normal file
16
event/event.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package event
|
||||
|
||||
type EventType string
|
||||
|
||||
const INSTANCE_VIEWPORT_RESIZE EventType = "instance viewport resize"
|
||||
const INSTANCE_DELETE EventType = "instance delete"
|
||||
const INSTANCE_NEW EventType = "instance new"
|
||||
const SESSION_END EventType = "session end"
|
||||
const SESSION_READY EventType = "session ready"
|
||||
|
||||
type Handler func(args ...interface{})
|
||||
|
||||
type EventApi interface {
|
||||
Emit(name EventType, args ...interface{})
|
||||
On(name EventType, handler Handler)
|
||||
}
|
||||
34
event/local_broker.go
Normal file
34
event/local_broker.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package event
|
||||
|
||||
import "sync"
|
||||
|
||||
type localBroker struct {
|
||||
sync.Mutex
|
||||
|
||||
handlers map[EventType][]Handler
|
||||
}
|
||||
|
||||
func NewLocalBroker() *localBroker {
|
||||
return &localBroker{handlers: map[EventType][]Handler{}}
|
||||
}
|
||||
|
||||
func (b *localBroker) On(name EventType, handler Handler) {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if b.handlers[name] == nil {
|
||||
b.handlers[name] = []Handler{}
|
||||
}
|
||||
b.handlers[name] = append(b.handlers[name], handler)
|
||||
}
|
||||
|
||||
func (b *localBroker) Emit(name EventType, args ...interface{}) {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if b.handlers[name] != nil {
|
||||
for _, handler := range b.handlers[name] {
|
||||
handler(args...)
|
||||
}
|
||||
}
|
||||
}
|
||||
31
event/local_broker_test.go
Normal file
31
event/local_broker_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLocalBroker(t *testing.T) {
|
||||
broker := NewLocalBroker()
|
||||
|
||||
called := 0
|
||||
receivedArgs := []interface{}{}
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
|
||||
broker.On(INSTANCE_NEW, func(args ...interface{}) {
|
||||
called++
|
||||
receivedArgs = args
|
||||
wg.Done()
|
||||
})
|
||||
broker.Emit(SESSION_READY)
|
||||
broker.Emit(INSTANCE_NEW, "foo", "bar")
|
||||
|
||||
wg.Wait()
|
||||
|
||||
assert.Equal(t, 1, called)
|
||||
assert.Equal(t, []interface{}{"foo", "bar"}, receivedArgs)
|
||||
}
|
||||
Reference in New Issue
Block a user