Skip to content

Commit

Permalink
feat: Added ListenerFunc (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
flc1125 authored Apr 15, 2023
1 parent 836e446 commit bef52a5
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 1 deletion.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ go get github.com/go-packagist/event/v3
```go
package main

import "github.com/go-packagist/event/v3"
import (
"fmt"
"github.com/go-packagist/event/v3"
)

type Event struct {
Stop bool
Expand Down Expand Up @@ -66,6 +69,9 @@ func main() {

d.Listen("event", &Listener1{})
d.Listen("event", &Listener2{})
d.Listen("event", event.ListenerFunc(func(event event.Event) {
fmt.Println(event.Name())
}))

d.Dispatch(e) // echo: listener1:event (because listener1 set Stop to true)

Expand Down
4 changes: 4 additions & 0 deletions example/main.go → _example/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"github.com/go-packagist/event/v3"
)

Expand Down Expand Up @@ -49,6 +50,9 @@ func main() {

d.Listen("event", &Listener1{})
d.Listen("event", &Listener2{})
d.Listen("event", event.ListenerFunc(func(event event.Event) {
fmt.Println(event.Name())
}))

d.Dispatch(e) // echo: listener1:event (because listener1 set Stop to true)

Expand Down
10 changes: 10 additions & 0 deletions dispatcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,13 @@ func TestFlush(t *testing.T) {
assert.Equal(t, 0, len(d.GetListeners("test1")))
assert.Equal(t, 0, len(d.GetListeners("test2")))
}

func TestDispatcher_ListenerFunc(t *testing.T) {
d := NewDispatcher()

event1 := newTestEvent("test1")

d.Listen("test1", ListenerFunc(func(event Event) {
assert.Equal(t, event1, event)
}))
}
1 change: 1 addition & 0 deletions event.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type Event interface {
Name() string
}

// StoppableEvent interface
type StoppableEvent interface {
IsPropagationStopped() bool
}
8 changes: 8 additions & 0 deletions listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@ package event
type Listener interface {
Handle(event Event)
}

// ListenerFunc listener function
type ListenerFunc func(event Event)

// Handle event
func (f ListenerFunc) Handle(event Event) {
f(event)
}

0 comments on commit bef52a5

Please sign in to comment.