event emitter
Node.js
const EventEmitter = require('events')
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter()
myEmitter.on('my-event', msg => {
console.log(msg)
})
myEmitter.on('my-other-event', msg => {
console.log(msg)
})
myEmitter.emit('my-event', 'hello world')
myEmitter.emit('my-other-event', 'hello other world')
Output
hello world
hello other world
Go
(closest thing is to use channels)
package main
import (
"fmt"
)
type MyEmitter map[string]chan string
func main() {
myEmitter := MyEmitter{}
myEmitter["my-event"] = make(chan string)
myEmitter["my-other-event"] = make(chan string)
go func() {
for {
select {
case msg := <-myEmitter["my-event"]:
fmt.Println(msg)
case msg := <-myEmitter["my-other-event"]:
fmt.Println(msg)
}
}
}()
myEmitter["my-event"] <- "hello world"
myEmitter["my-other-event"] <- "hello other world"
}
Output
hello world
hello other world
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .