This fixes #4259. Only displatching the event for the top node, and cleaning up the code to make it more readable and easier to understand.