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:
parent
0e2ca2a14a
commit
c8ca415b4b
@ -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) {
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
10
table.go
10
table.go
@ -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 {
|
||||
|
@ -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)
|
||||
|
Loading…
x
Reference in New Issue
Block a user