gookit / event

📢 Lightweight event manager and dispatcher implements by Go. Go实现的轻量级的事件管理、调度程序库, 支持设置监听器的优先级, 支持使用通配符来进行一组事件的监听
https://pgk.go.dev/github.com/gookit/event
MIT License
501 stars 59 forks source link

RemoveListener support closure function; fix: #9 #41

Closed RelicOfTesla closed 1 year ago

RelicOfTesla commented 1 year ago

fix https://github.com/gookit/event/issues/9

RelicOfTesla commented 1 year ago

还有个简易方法,使用reflect.Value做比较。 即

func getListenCompareKey(src Listener) reflect.Value {
    return reflect.ValueOf(src)
}

缺点就是不支持传入reflect.Struct的Listener,必须是指针型的Listener或func。也就是必须On(...)时,对传入的Listener进行判断,panic掉struct的Listener,强制要求&xxx{}或new或ListenerFunc类型进来

func (em *Manager) addListenerItem(name string, li *ListenerItem) {
    if name != Wildcard {
        name = goodName(name)
    }
    if li.Listener == nil {
        panic("event: the event '" + name + "' listener cannot be empty")
    }
    if reflect.ValueOf(li.Listener).Kind() == reflect.Struct {
        panic("must use pointer Listener, don't use struct Listener")
    }

    // exists, append it.
    if lq, ok := em.listeners[name]; ok {
        lq.Push(li)
    } else { // first add.
        em.listenedNames[name] = 1
        em.listeners[name] = (&ListenerQueue{}).Push(li)
    }
}

我另外push一个过来

inhere commented 1 year ago

@RelicOfTesla 感谢PR 👍