mirror of https://github.com/pocke/goevent.git
Implement Off
This commit is contained in:
parent
148cb440fb
commit
37afb7b77b
15
goevent.go
15
goevent.go
|
@ -61,8 +61,19 @@ func (p *Event) On(f interface{}) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (p *Event) Off() {
|
||||
panic(fmt.Errorf("Off() has not been implemented yet."))
|
||||
func (p *Event) Off(f interface{}) {
|
||||
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) {
|
||||
|
|
|
@ -92,3 +92,38 @@ func TestOnWhenInvalidArgs(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue