github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/event/target.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package event 4 5 import ( 6 "sync" 7 8 "../protocol" 9 ) 10 11 // EventTarget must declare separately for each protocol.EventMainType types. 12 // otherwise need this struct that use 2KB for each instance. 13 // cl [256]*[]customListener // 256 is max protocol.EventMainType 14 // Or use map but need some benchmarks to check performance. 15 type EventTarget struct { 16 sync sync.Mutex 17 lls *[]customListener 18 } 19 20 type customListener struct { 21 eventSubType protocol.EventSubType 22 eventListener protocol.EventListener 23 } 24 25 func (et *EventTarget) DispatchEvent(event protocol.LogEvent) { 26 // TODO::: add atomic mechanism?? 27 var lls = *et.lls 28 var eventSubType = event.SubType() 29 for i := 0; i < len(lls); i++ { 30 var cl = lls[i] 31 if cl.eventSubType == protocol.EventSubType_Unset || cl.eventSubType == eventSubType { 32 cl.eventListener.EventHandler(event) 33 } 34 } 35 } 36 37 func (et *EventTarget) AddEventListener(mainType protocol.EventMainType, subType protocol.EventSubType, callback protocol.EventListener, options protocol.AddEventListenerOptions) { 38 et.sync.Lock() 39 var lls = *et.lls 40 var ln = len(lls) 41 var newLLS = make([]customListener, ln+1) 42 copy(newLLS, lls) 43 newLLS[ln-1] = customListener{subType, callback} 44 et.lls = &newLLS 45 // TODO::: handle options here or caller layer must handle it? 46 et.sync.Unlock() 47 } 48 49 func (et *EventTarget) RemoveEventListener(mainType protocol.EventMainType, subType protocol.EventSubType, callback protocol.EventListener, options protocol.EventListenerOptions) { 50 et.sync.Lock() 51 var lls = *et.lls 52 var ln = len(lls) 53 for i := 0; i < ln; i++ { 54 var cl = lls[i] 55 if cl.eventSubType == subType && cl.eventListener == callback { 56 var newLLS = make([]customListener, ln-1) 57 copy(newLLS, lls[:i]) 58 copy(newLLS[i:], lls[i+1:]) 59 et.lls = &newLLS 60 break 61 } 62 } 63 et.sync.Unlock() 64 }