Skip to content

Commit

Permalink
✨ feat: improve emit
Browse files Browse the repository at this point in the history
  • Loading branch information
jingyuexing committed Jun 16, 2024
1 parent 43d3d31 commit 8938162
Showing 1 changed file with 30 additions and 31 deletions.
61 changes: 30 additions & 31 deletions emit.go
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() }()
}

0 comments on commit 8938162

Please sign in to comment.