地址: github.com/lockp111/go-eventbusgit
參考go-observable, 可是那個代碼有問題, 會由於map同時讀寫出現crash, 我修復以後提交給做者也一直不理我, 因而就本身fork一份自用, 後來以爲反射調用的損耗仍是比較大的, 並且使用func若是不注意, 有可能出現兩個相同的func, 因而改爲interface, Benchmark顯示提高很是大github
go get -u github.com/lockp111/go-eventbus
Create a new bus struct referencesegmentfault
bus := eventbus.New()
Subscribe eventurl
type ready struct{ } func (e ready) Dispatch(msg interface{}){ fmt.Println("I am ready!") } bus.On("ready", &ready{})
You can also subscribe multiple events for example:spa
type run struct{ } func (e run) Dispatch(msg interface{}){ fmt.Println("I am run!") } bus.On("ready", &ready{}, &ready{}).On("run", &run{})
Unsubscribe eventcode
e := &ready{} bus.On("ready", e) bus.Off("ready", e)
You can also unsubscribe multiple events for example:事件
e1 := &ready{} e2 := &ready{} bus.On("ready", e1, e2) bus.Off("ready", e1, e2)
You can unsubscribe all events for example:ip
bus.On("ready", &ready{}, &ready{}) bus.Off("ready")
You can unsubscribe all topics for example:get
bus.On("ready", &ready{}, &ready{}) bus.On("run", &run{}) bus.Off(ALL)
Dispatch eventsstring
bus.Trigger("ready")
You can also dispatch multiple events for example:
bus.Trigger("ready", &struct{"1"}, &struct{"2"})
You can also dispatch all events for example:
bus.Trigger(ALL, &struct{"1"})