手寫一個簡單的EventDispatcher [Golang] 事件注冊機制
-
- 背景
- 核心代碼
- 位址
- 運作結果
背景
項目中用到了eventDispatcher,但是golang沒有,是以1V1借助laya的思想寫了一個golang的版本
核心代碼
RegisterEvent/RemoveEvent/DispatchEvent
// DispatchEvent
func (p *_EventManager) DispatchEvent(tp string, args interface{}) {
if f, ok := p.eventMap[tp]; ok {
err := f.Exec(args)
if err != nil {
fmt.Println(fmt.Sprintf("%+v", err.Error()))
}
}
}
// RegisterEvent
func (p *_EventManager) RegisterEvent(tp string, f TFunction) {
e, ok := p.eventMap[tp]
if ok {
e.Add(&f)
} else {
tEvent := &_Event{
functions: []*TFunction{&f},
}
p.eventMap[tp] = tEvent
}
}
// RemoveEvent
func (p *_EventManager) RemoveEvent(tp string, f TFunction) {
if e, ok := p.eventMap[tp]; ok {
e.Remove(&f)
return
}
}
位址
github