teventemitter.nim 922 B

123456789101112131415161718192021222324252627282930313233
  1. discard """
  2. output: "pie"
  3. """
  4. import tables, lists
  5. type
  6. EventArgs = object of RootObj
  7. EventEmitter = object of RootObj
  8. events*: Table[string, DoublyLinkedList[proc(e: EventArgs) {.nimcall.}]]
  9. proc emit*(emitter: EventEmitter, event: string, args: EventArgs) =
  10. for fn in nodes(emitter.events[event]):
  11. fn.value(args) #call function with args.
  12. proc on*(emitter: var EventEmitter, event: string,
  13. fn: proc(e: EventArgs) {.nimcall.}) =
  14. if not hasKey(emitter.events, event):
  15. var list: DoublyLinkedList[proc(e: EventArgs) {.nimcall.}]
  16. add(emitter.events, event, list) #if not, add it.
  17. append(emitter.events[event], fn)
  18. proc initEmitter(emitter: var EventEmitter) =
  19. emitter.events = initTable[string,
  20. DoublyLinkedList[proc(e: EventArgs) {.nimcall.}]]()
  21. var
  22. ee: EventEmitter
  23. args: EventArgs
  24. initEmitter(ee)
  25. ee.on("print", proc(e: EventArgs) = echo("pie"))
  26. ee.emit("print", args)