event emitter


Node.js

  1. const EventEmitter = require('events')
  2. class MyEmitter extends EventEmitter {}
  3. const myEmitter = new MyEmitter()
  4. myEmitter.on('my-event', msg => {
  5. console.log(msg)
  6. })
  7. myEmitter.on('my-other-event', msg => {
  8. console.log(msg)
  9. })
  10. myEmitter.emit('my-event', 'hello world')
  11. myEmitter.emit('my-other-event', 'hello other world')

Output

  1. hello world
  2. hello other world

Go

(closest thing is to use channels)

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type MyEmitter map[string]chan string
  6. func main() {
  7. myEmitter := MyEmitter{}
  8. myEmitter["my-event"] = make(chan string)
  9. myEmitter["my-other-event"] = make(chan string)
  10. go func() {
  11. for {
  12. select {
  13. case msg := <-myEmitter["my-event"]:
  14. fmt.Println(msg)
  15. case msg := <-myEmitter["my-other-event"]:
  16. fmt.Println(msg)
  17. }
  18. }
  19. }()
  20. myEmitter["my-event"] <- "hello world"
  21. myEmitter["my-other-event"] <- "hello other world"
  22. }

Output

  1. hello world
  2. hello other world