From cd74fa99fbba3df13da184eebce03d025ddace3f Mon Sep 17 00:00:00 2001 From: Anthony Laibe Date: Wed, 10 Nov 2021 20:48:08 +0100 Subject: [PATCH] fix: collect event before executing them (#99) This is in order to avoid missing events due to mutating the table while iterating on it --- eventemitter.nim | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/eventemitter.nim b/eventemitter.nim index 7ea5eb2..6db028f 100644 --- a/eventemitter.nim +++ b/eventemitter.nim @@ -34,8 +34,16 @@ proc once*(this:EventEmitter, name:string, handler:Handler): void = proc emit*(this:EventEmitter, name:string, args:Args): void = if this.events.hasKey(name): + # collect the handlers before executing them + # because of 'once' proc, we also mutate + # this.events. This can cause unexpected behaviour + # while having an iterator on this.events + var handlers: seq[Handler] = @[] for (id, handler) in this.events[name].pairs: - handler(args) + handlers.add(handler) + + for i in 0..len(handlers)-1: + handlers[i](args) when isMainModule: block: