patterncsharpMinor
Invoking only the last registered event handler
Viewed 0 times
lasttheregisteredinvokinghandleronlyevent
Problem
We are building a game and we have a dialog system. Dialogs may open and stack on top of one another.
When every dialog opens, it registers itself to handle the BackButtonPressed event:
When the dialog closed, it unhooks from the event:
The problem is, we'd like the event to raise the event handler of the active dialog only (the active dialog is the last one registered to the event.
A proposed solution was to:
Here's an example in code, is this the proper way of doing this?
Raising the event:
When every dialog opens, it registers itself to handle the BackButtonPressed event:
AppHelper.OnBackPressed += HandleBackPressed;When the dialog closed, it unhooks from the event:
AppHelper.OnBackPressed -= HandleBackPressed;The problem is, we'd like the event to raise the event handler of the active dialog only (the active dialog is the last one registered to the event.
A proposed solution was to:
- Manually create the add and remove methods for the event
- Keeping registered handlers in a list.
- When raising the event, call the last handler in the list
Here's an example in code, is this the proper way of doing this?
private static List backPressed = new List();
public static event BackPressed OnBackPressed
{
add
{
backPressed.Add(value);
}
remove
{
if(backPressed.Contains(value))
{
backPressed.Remove(value);
}
}
}Raising the event:
backPressed[backPressed.Count - 1].Invoke();Solution
Yes, this is a reasonable way to implement the event. Another would be use the normal even implementation (without explicit
But I think the fundamental problem here is that what you want doesn't really behave like an event, so it probably shouldn't be an event.
What I would probably do is to make the abstraction something like “a collection of open
That way, you can easily access the top-most open
add and remove) and get the last subscriber using GetInvocationList().But I think the fundamental problem here is that what you want doesn't really behave like an event, so it probably shouldn't be an event.
What I would probably do is to make the abstraction something like “a collection of open
Dialogs”, not “a collection of delegates that are going to be invoked when the back button is pressed”.That way, you can easily access the top-most open
Dialog and invoke its HandleBackPressed() method. But you could also use it for other purposes. So this would make your code more flexible, without adding much complexity.Context
StackExchange Code Review Q#73531, answer score: 2
Revisions (0)
No revisions yet.