Implement Off

This commit is contained in:
pocke 2015-01-11 22:33:06 +09:00
parent 148cb440fb
commit 37afb7b77b
2 changed files with 48 additions and 2 deletions

View File

@ -61,8 +61,19 @@ func (p *Event) On(f interface{}) error {
return nil return nil
} }
func (p *Event) Off() { func (p *Event) Off(f interface{}) {
panic(fmt.Errorf("Off() has not been implemented yet.")) fn := reflect.ValueOf(f)
p.lmu.Lock()
defer p.lmu.Unlock()
l := len(p.listeners)
for i := 0; i < l; i++ {
if fn == p.listeners[i] {
p.listeners = append(p.listeners[:i], p.listeners[i+1:]...)
l--
i--
}
}
} }
func (p *Event) checkFuncSignature(f interface{}) (*reflect.Value, error) { func (p *Event) checkFuncSignature(f interface{}) (*reflect.Value, error) {

View File

@ -92,3 +92,38 @@ func TestOnWhenInvalidArgs(t *testing.T) {
t.Error("Should return error when different args type. But got nil") t.Error("Should return error when different args type. But got nil")
} }
} }
func TestOff(t *testing.T) {
p := goevent.New()
i := 0
j := 0
k := 0
p.On(func() { j++ })
f := func() { i++ }
p.On(f)
p.On(func() { k++ })
p.Trigger()
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
}
if j != 1 {
t.Errorf("j expected 1, but got %d", j)
}
if k != 1 {
t.Errorf("k expected 1, but got %d", k)
}
p.Off(f)
p.Trigger()
if i != 1 {
t.Errorf("i expected 1, but got %d", i)
}
if j != 2 {
t.Errorf("j expected 2, but got %d", j)
}
if k != 2 {
t.Errorf("k expected 2, but got %d", k)
}
}