Skip to content

Commit

Permalink
Implement Off
Browse files Browse the repository at this point in the history
  • Loading branch information
pocke committed Jan 11, 2015
1 parent 148cb44 commit 37afb7b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
15 changes: 13 additions & 2 deletions goevent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
35 changes: 35 additions & 0 deletions goevent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 37afb7b

Please sign in to comment.