2014-06-12 02:37:20 +08:00
|
|
|
package gobot
|
|
|
|
|
2014-07-14 11:27:38 +08:00
|
|
|
type callback struct {
|
|
|
|
f func(interface{})
|
|
|
|
once bool
|
|
|
|
}
|
|
|
|
|
2014-06-12 02:37:20 +08:00
|
|
|
type Event struct {
|
|
|
|
Chan chan interface{}
|
2014-07-14 11:27:38 +08:00
|
|
|
Callbacks []callback
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewEvent() *Event {
|
|
|
|
e := &Event{
|
|
|
|
Chan: make(chan interface{}, 1),
|
2014-07-14 11:27:38 +08:00
|
|
|
Callbacks: []callback{},
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
e.Read()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return e
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Event) Write(data interface{}) {
|
|
|
|
select {
|
|
|
|
case e.Chan <- data:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Event) Read() {
|
|
|
|
for s := range e.Chan {
|
2014-07-15 04:34:46 +08:00
|
|
|
tmp := []callback{}
|
2014-07-14 11:27:38 +08:00
|
|
|
for i := range e.Callbacks {
|
|
|
|
go e.Callbacks[i].f(s)
|
|
|
|
if !e.Callbacks[i].once {
|
|
|
|
tmp = append(tmp, e.Callbacks[i])
|
|
|
|
}
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
2014-07-14 11:27:38 +08:00
|
|
|
e.Callbacks = tmp
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
}
|