-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
43d3d31
commit 8938162
Showing
1 changed file
with
30 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() }() | ||
} |