craftyjs/Crafty — pull request #832 by starwed (2014-11-12 21:52:46+00:00)
Title: Implement a new strategy for avoiding event queue mutation

The event callback queue can mutate in ways that mess up the iteration. There are two cases we need to handle:
- While iterating through an event's callbacks, a new one is added. This should not be triggered.
- When a callback is removed, we shouldn't actually mutate the callbacks array if this iteration was triggered in the middle of an iteration over the same array. (We currently kind of half-handle this case, but there's a better way.)

The first is solved by registering the callback array's length at the time iteration starts. The second is solved by adding a depth counter to each callback array. It's iterated at the beginning of iteration, and decremented at the end. Items are removed from the callbacks array only when the counter indicates a depth of 1.

This patch adds a test for the addition of a callback mid-event. It also adds one for binding/triggering groups of entities at once, since I noticed a typo I introduced while modifying the code wasn't being caught by the existing tests.

This fixes #824.