Adding keyboard obersver with `insertFirst=true` from observer causes infinite loop

I’m not entirely sure this is is a bug, but it certainly breaks things quite well. Possibly it’s working as intended.

Background: I have a player controller with different tools, overriding the behaviour. So when I activate “Tool A”, I’d like it to have priority over the regular player input. You can activate/deactivate some of these tools with keyboard input.

Can be worked around by adding the observer delayed with setTimeout.

Here’s a playground: Babylon.js Playground

To reproduce: Press ‘K’ and wait for the ‘O’ :slight_smile:

Just realised I should probably be using eventState.skipNextObservers = true; here (and that does work).

Though, technically, if you insert it “first”, it’s not a “next” observer in any sense. Since you would have inserted it “before” the current observer.

Edit: Also, probably worth noting it only goes into the infinite loop when you insert it first.

in your case I would probably rely on a flag instead like if you press K set your flag to true an when pressing O you could check the flag value.

Adding extra listeners is not bad but complexify the code a bit :slight_smile:

The playground is a simplified example to show the issue.

Didn’t look at the code, but probably comes down to looping over the array of observers while adding to the front.

It’s by no means a high priority issue, but say I for some reason need to not skip the next observers while adding to the front…

Not a javascript buff, but in other languages iterators can be used to avoid issues like this.