66 lines
1.1 KiB
Go
66 lines
1.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"runtime/debug"
|
||
|
"time"
|
||
|
|
||
|
emitter "git.pyer.club/kingecg/goemitter"
|
||
|
)
|
||
|
|
||
|
type St struct {
|
||
|
Name string
|
||
|
}
|
||
|
|
||
|
func (s *St) Print(data ...interface{}) {
|
||
|
fmt.Println(s.Name)
|
||
|
fmt.Println(data...)
|
||
|
}
|
||
|
|
||
|
type A struct {
|
||
|
Name string
|
||
|
}
|
||
|
|
||
|
func (a *A) Exec(data ...interface{}) {
|
||
|
fmt.Println(a.Name, data)
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
|
||
|
s := &St{Name: "testeer"}
|
||
|
em := emitter.NewEmitter()
|
||
|
emh := em.On("test", func(data ...interface{}) {
|
||
|
fmt.Println("should be canceled next")
|
||
|
fmt.Println(data...)
|
||
|
|
||
|
})
|
||
|
|
||
|
em.On("test", s.Print)
|
||
|
em.Once("test", func(data ...interface{}) {
|
||
|
s := fmt.Sprint(data...)
|
||
|
fmt.Println(interface{}("Once"), s)
|
||
|
})
|
||
|
func() {
|
||
|
em.On("test", func(data ...interface{}) {
|
||
|
fmt.Println("函数内匿名函数被调用")
|
||
|
})
|
||
|
}()
|
||
|
func() {
|
||
|
a := &A{Name: "ATEST"}
|
||
|
em.On("test", a.Exec)
|
||
|
}()
|
||
|
em.EmitSync("test", "hello", "world")
|
||
|
emh.Remove()
|
||
|
em.Emit("test", "hello", "world2")
|
||
|
|
||
|
defer func() {
|
||
|
if r := recover(); r != nil {
|
||
|
log.Println("Recovered in main:", r)
|
||
|
// 打印当前所有 goroutine 的堆栈信息
|
||
|
log.Println(string(debug.Stack()))
|
||
|
}
|
||
|
}()
|
||
|
time.Sleep(10 * time.Second)
|
||
|
}
|