EventEmitter for golang

emitter.go
复制

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
}

大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!