Folks,
I have a feeling there's a classic design pattern that covers this case, but I don't have a reference handy.
I have a situation where a user clicks a button and another part of the web page responds. What's unusual (or at least inconvenient) is that the button and the reponding part of the web page are in very different control hierarchies, both in terms of distance to common ancestor and in terms of application concern. They're both inner parts of a series of (separate) black boxes.
I have not been able to come up with an elegant way for the one to trigger the other. I do not want to have to raise a series of events up to the top of the control hierarchy and then call a series of nested methods to make the desired effect happen. ("effect" != visual effect; I can't solve this with jQuery) I want the event and the responder to remain ignorant of each other: I will not violate separation of concer开发者_运维技巧ns by having the latter know about and directly subscribe to an event generated by the former. I've considered a number of other inelegant solutions, but I won't bore you by listing them off.
Basically I guess I need a way to implement a publisher-subscriber model for events in which anything can subscribe to anything.
I'm using .Net 4.0. Any nice frameworks that do this? Any easy ways to implement it?
Thanks a lot,
Ann L.
Sounds like you need an EventAggregator. You should find the implementation in the Composite Application Library.
The EventAggregator allows you to register to notifications and raise them from completely separated parts of the application.
For server side events you can use:
The Reactive Extensions (Rx)...
http://msdn.microsoft.com/en-us/data/gg577609
For Client side events you can use:
Backbone JS
http://documentcloud.github.com/backbone/
Knockout JS
http://knockoutjs.com/
You mentioned you couldn't use jQuery may I ask why?
I'm not sure if I understand you correctly, but it sounds like you want to assign multiple buttons to the same event handler, which you can do like this:
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" ... />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" ... />
In the code-behind:
protected void Button_Click(object sender, EventArgs e)
{
if (sender.Equals(Button1))
{
//Button1 logic
}
else if (sender.Equals(Button2))
{
//Button2 logic
}
}
EDIT
Based on your comment, it sounds like you might need an event handler. If so, try something like this:
public event EventHandler ButtonClick;
protected void Button_Click(object sender, EventArgs e)
{
if (this.ButtonClick != null)
this.ButtonClick(sender, e);
}
精彩评论