From 89381621260fc9721b88dc8d18d19422bd8e40a3 Mon Sep 17 00:00:00 2001 From: jingyuexing <19589872+jingyuexing@users.noreply.github.com> Date: Sun, 16 Jun 2024 08:18:05 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20improve=20emit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- emit.go | 61 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/emit.go b/emit.go index 9166ab3..efa9696 100644 --- a/emit.go +++ b/emit.go @@ -1,49 +1,48 @@ package utils - import "sync" func Emit[T any]() (handler func(name string, args ...T), listener func(name string, callback func(args ...T)), errorHandler func(err error)) { - eventList := make(map[string][]func(args ...T)) - handler = func(name string, args ...T) { - err := recover() - for _, call := range eventList[name] { - call(args...) - } - if err != nil { - errorHandler(err.(error)) - } - } - - listener = func(name string, callback func(args ...T)) { - eventList[name] = append(eventList[name], callback) - } - - return handler, listener, errorHandler + eventList := make(map[string][]func(args ...T)) + handler = func(name string, args ...T) { + err := recover() + for _, call := range eventList[name] { + call(args...) + } + if err != nil { + errorHandler(err.(error)) + } + } + + listener = func(name string, callback func(args ...T)) { + eventList[name] = append(eventList[name], callback) + } + + return handler, listener, errorHandler } type EventEmit struct { - mutex sync.Mutex - events map[string][](func(args ...any)) + mutex sync.Mutex + events map[string][](func(args ...any)) } func NewEventEmit() *EventEmit { - return &EventEmit{ - mutex: sync.Mutex{}, - events: make(map[string][]func(args ...any)), - } + return &EventEmit{ + mutex: sync.Mutex{}, + events: make(map[string][]func(args ...any)), + } } func (e *EventEmit) On(name string, callback func(args ...any)) { - e.mutex.Lock() - e.events[name] = append(e.events[name], callback) - defer e.mutex.Unlock() + e.mutex.Lock() + defer func() { e.mutex.Unlock() }() + e.events[name] = append(e.events[name], callback) } func (e *EventEmit) Emit(name string, args ...any) { - e.mutex.Lock() - for _, call := range e.events[name] { - call(args...) - } - defer e.mutex.Unlock() + e.mutex.Lock() + for _, call := range e.events[name] { + call(args...) + } + defer func() { e.mutex.Unlock() }() }