pocke.goevent/table.go

72 lines
1.2 KiB
Go
Raw Normal View History

2015-01-11 15:53:31 +08:00
package goevent
2015-01-12 13:51:59 +08:00
import "sync"
2015-01-11 15:53:31 +08:00
2015-01-17 16:44:47 +08:00
// Table is an event table.
2015-01-11 15:53:31 +08:00
type Table interface {
2015-01-17 16:44:47 +08:00
Trigger(name string, args ...interface{}) error
// f is a function
On(name string, f interface{}) error
Off(name string, f interface{}) error
// Destroy a event
Destroy(name string) error
2015-01-11 15:53:31 +08:00
}
type table struct {
2015-01-17 15:53:23 +08:00
events map[string]Event
2015-01-11 15:53:31 +08:00
mu sync.RWMutex
}
2015-01-17 16:44:47 +08:00
// NewTable creates a new event table.
2015-01-11 15:53:31 +08:00
func NewTable() Table {
return &table{
2015-01-17 15:53:23 +08:00
events: map[string]Event{},
2015-01-11 15:53:31 +08:00
}
}
func (t *table) Trigger(name string, args ...interface{}) error {
t.mu.RLock()
defer t.mu.RUnlock()
ev, ok := t.events[name]
if !ok {
2015-01-12 13:51:59 +08:00
return newEventNotDefined(name)
2015-01-11 15:53:31 +08:00
}
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-12 11:34:04 +08:00
func (t *table) Off(name string, f interface{}) error {
2015-01-11 21:51:20 +08:00
t.mu.Lock()
defer t.mu.Unlock()
e, ok := t.events[name]
if !ok {
2015-01-12 13:51:59 +08:00
return newEventNotDefined(name)
2015-01-11 21:51:20 +08:00
}
2015-01-12 11:34:04 +08:00
return e.Off(f)
2015-01-11 21:51:20 +08:00
}
2015-01-12 11:08:51 +08:00
func (t *table) Destroy(name string) error {
if _, ok := t.events[name]; !ok {
2015-01-12 13:51:59 +08:00
return newEventNotDefined(name)
2015-01-12 11:08:51 +08:00
}
delete(t.events, name)
return nil
}
2015-01-11 15:53:31 +08:00
var _ Table = &table{}