Skip to content

Instantly share code, notes, and snippets.

@axetroy

axetroy/emitter.go

Last active Nov 27, 2017
Embed
What would you like to do?
EventEmitter for golang
package pool
import "time"
type Event struct {
Time time.Time
Name string
Data interface{}
Id string
}
type EventEmitter struct {
config *Config
events map[string][]EventHandler
}
type Config struct {
MaxListeners int
}
type EventHandler func(event Event)
var defaultConfig = Config{
MaxListeners: 15,
}
func New(c *Config) *EventEmitter {
if c == nil {
c = &defaultConfig
}
return &EventEmitter{
config: c,
}
}
/**
Listen on something
*/
func (e *EventEmitter) on(eventName string, handler EventHandler) *EventEmitter {
if e.events[eventName] == nil {
list := *new([]EventHandler)
e.events[eventName] = list
}
list := e.events[eventName]
list = append(list, handler)
e.events[eventName] = list
return e
}
/**
Listen on something once
*/
func (e *EventEmitter) once(eventName string, handler EventHandler) *EventEmitter {
if e.events[eventName] == nil {
list := *new([]EventHandler)
e.events[eventName] = list
}
list := e.events[eventName]
list = append(list, handler)
e.events[eventName] = list
return e
}
/**
Event event
*/
func (e *EventEmitter) emit(eventName string, data interface{}) *EventEmitter {
list := e.events[eventName]
for _, handler := range list {
handler(Event{
Time: time.Now(),
Name: eventName,
Id: "123123",
Data: data,
})
}
return e
}
/**
Clear listener
*/
func (e *EventEmitter) clear(eventName *string) *EventEmitter {
if eventName == nil {
// clear all event listener
for name := range e.events {
e.events[name] = nil
}
} else {
e.events[*eventName] = nil
}
return e
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.