I'm making a game GUI and basically each Widget can have other widgets which listen to mouse or keyboard events. Anyone of these can consume the event too (and then any subsequent ones will not receive it.
The part I'm unsure for 开发者_StackOverflowis if the order shoud be:
Send event to Target Widget
if(event is not consumed)
{
Send each listener the event
}
or
Send each listener the event
if(event is not consumed)
{
Send event to Target Widget
}
Which one makes most sense?
Thanks
The best event model I've every used is from the Tk toolkit (and I've used perhaps a dozen toolkits professionally during my career). The naive description is that the event starts from the most specific (the actual widget in which the widget occured) up a chain to the least specific (a global binding).
It's a little more complex than that, but that's the general idea, and it works extremely well. At each step in the process from most specific to most generic, each handler has the opportunity to say "I've handled this event" and to stop it from propagating. Or, it can handle or ignore the error while also letting it percolate up.
If you're rolling your own event mechanism you owe it to yourself to study Tk's "bindtag" mechanism. The default behavior is as I described, but the bindtag mechanism is much more powerful because it lets you alter the order for each widget. I've found this invaluable because, while the standard behavior works in 95% of the cases, you want to be able to support that other 5%.
I would probably use the first. It makes more logical sense to me (at least) to not send the event out unless it's not wanted.
I mean, you wouldn't send out invitations (event) to your friends (the listeners) if you cancelled the party (the original event has been consumed).
精彩评论