Collect active substates before sending events to them.

This is to address a bug with the following scenario:

stateA handles eventA and during the handling, activates stateB.

In the existing code, if stateB happens to also handle eventA and by chance appears later in the substates enumeration, it will also try to handle eventA because it is now active.

The PR addresses this by first collecting an array of all active events and only after the tree has been traversed and all events collected, then having each state handle the event.