1
0
mirror of https://github.com/pocke/goevent.git synced 2025-04-24 13:48:55 +08:00

Off return nil

This commit is contained in:
pocke 2015-01-12 12:34:04 +09:00
parent 0e2ca2a14a
commit c8ca415b4b
4 changed files with 26 additions and 8 deletions

View File

@ -61,19 +61,26 @@ func (p *Event) On(f interface{}) error {
return nil
}
func (p *Event) Off(f interface{}) {
func (p *Event) Off(f interface{}) error {
fn := reflect.ValueOf(f)
p.lmu.Lock()
defer p.lmu.Unlock()
l := len(p.listeners)
m := l // for error check
for i := 0; i < l; i++ {
if fn == p.listeners[i] {
// XXX: GC Ref: http://jxck.hatenablog.com/entry/golang-slice-internals
p.listeners = append(p.listeners[:i], p.listeners[i+1:]...)
l--
i--
}
}
if l == m {
return fmt.Errorf("Listener does't exists")
}
return nil
}
func (p *Event) checkFuncSignature(f interface{}) (*reflect.Value, error) {

View File

@ -115,7 +115,10 @@ func TestOff(t *testing.T) {
t.Errorf("k expected 1, but got %d", k)
}
p.Off(f)
err := p.Off(f)
if err != nil {
t.Error(err)
}
p.Trigger()
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
@ -126,4 +129,9 @@ func TestOff(t *testing.T) {
if k != 2 {
t.Errorf("k expected 2, but got %d", k)
}
err = p.Off(f)
if err == nil {
t.Errorf("should return error when Listener doesn't exists. but got nil")
}
}

View File

@ -8,7 +8,7 @@ import (
type Table interface {
On(string, interface{}) error
Trigger(string, ...interface{}) error
Off(string, interface{})
Off(string, interface{}) error
Destroy(string) error
}
@ -47,16 +47,16 @@ func (t *table) On(name string, f interface{}) error {
return ev.On(f)
}
// XXX: return error?
func (t *table) Off(name string, f interface{}) {
func (t *table) Off(name string, f interface{}) error {
t.mu.Lock()
defer t.mu.Unlock()
e, ok := t.events[name]
if !ok {
return
return fmt.Errorf("%s event has not been defined yet.", name)
}
e.Off(f)
return e.Off(f)
}
func (t *table) Destroy(name string) error {

View File

@ -44,7 +44,10 @@ func TestTableOff(t *testing.T) {
f := func() { i++ }
ta.On("foo", f)
ta.Trigger("foo")
ta.Off("foo", f)
err := ta.Off("foo", f)
if err != nil {
t.Error(err)
}
ta.Trigger("foo")
if i != 1 {
t.Errorf("i expected 1, but got %d", i)