pocke.goevent/table.go

71 lines
1.1 KiB
Go
Raw Normal View History

2015-01-11 15:53:31 +08:00
package goevent
import (
"fmt"
"sync"
)
type Table interface {
On(string, interface{}) error
Trigger(string, ...interface{}) error
2015-01-11 21:51:20 +08:00
Off(string, interface{})
2015-01-12 11:08:51 +08:00
Destroy(string) error
2015-01-11 15:53:31 +08:00
}
type table struct {
events map[string]*Event
mu sync.RWMutex
}
func NewTable() Table {
return &table{
events: map[string]*Event{},
}
}
func (t *table) Trigger(name string, args ...interface{}) error {
t.mu.RLock()
defer t.mu.RUnlock()
ev, ok := t.events[name]
if !ok {
return fmt.Errorf("%s event has not been defined yet.", name)
}
return ev.Trigger(args...)
}
func (t *table) On(name string, f interface{}) error {
t.mu.Lock()
defer t.mu.Unlock()
ev, ok := t.events[name]
if !ok {
ev = New()
t.events[name] = ev
}
return ev.On(f)
}
2015-01-11 21:51:20 +08:00
// XXX: return error?
func (t *table) Off(name string, f interface{}) {
t.mu.Lock()
defer t.mu.Unlock()
e, ok := t.events[name]
if !ok {
return
}
e.Off(f)
}
2015-01-12 11:08:51 +08:00
func (t *table) Destroy(name string) error {
if _, ok := t.events[name]; !ok {
return fmt.Errorf("%s event has not been defined yet.", name)
}
delete(t.events, name)
return nil
}
2015-01-11 15:53:31 +08:00
var _ Table = &table{}