package events import ( "sync" "github.com/google/uuid" ) type syncEventListener struct { id string cb func(event string, data any) } type SyncEmitter struct { sync.Mutex listeners map[string][]syncEventListener } func NewSyncEventListener(cb func(event string, data any)) *syncEventListener { return &syncEventListener{ id: uuid.NewString(), cb: cb, } } func NewSyncEmitter() *SyncEmitter { return &SyncEmitter{ listeners: make(map[string][]syncEventListener), } } func (e *SyncEmitter) Emit(event string, data any) { e.Lock() defer e.Unlock() targets := e.listeners[event] for _, listener := range targets { listener.cb(event, data) } } func (e *SyncEmitter) AddListener(event string, listener syncEventListener) { e.Lock() defer e.Unlock() e.listeners[event] = append(e.listeners[event], listener) } func (e *SyncEmitter) RemoveListener(event string, listener syncEventListener) { e.Lock() defer e.Unlock() for i, l := range e.listeners[event] { if l.id == listener.id { e.listeners[event] = append(e.listeners[event][:i], e.listeners[event][i+1:]...) } } }