From edbde752af768c67188aea5a0fd66b9242a30343 Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Fri, 29 May 2020 01:21:02 -0500 Subject: [PATCH] Start on an event handler. It may work or not :shrug: --- src/event_handler.nim | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/event_handler.nim diff --git a/src/event_handler.nim b/src/event_handler.nim new file mode 100644 index 0000000..18a7227 --- /dev/null +++ b/src/event_handler.nim @@ -0,0 +1,27 @@ +import tables, hashes, sequtils + +type + BaseEvent* = object + name*: string + +proc hash[T: object](o: T): Hash = + for k, v in o.fieldPairs: + result = result !& v.hash + result = !$result + +# Table storing all the event listeners +let eventListeners = newTable[BaseEvent, seq[proc()]]() + +proc registerEventListener*(event: BaseEvent, listener: proc()) = + if (eventListeners.hasKey(event)): + var listeners = eventListeners[event] + listeners.add(listener) + else: + let tmp = @[listener] + eventListeners.add(event, tmp) + +proc dispatchEvent(event: BaseEvent) = + if (eventListeners.hasKey(event)): + let listeners = eventListeners[event] + for index, eventListener in listeners.pairs: + eventListener() \ No newline at end of file