fix: collect event before executing them (#99)

This is in order to avoid missing events due
to mutating the table while iterating on it
This commit is contained in:
Anthony Laibe 2021-11-10 20:48:08 +01:00 committed by GitHub
parent 0a8674c5cd
commit cd74fa99fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 1 deletions

View File

@ -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: