Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple subscribers to single ASP.NET UserControl event?

I am puzzling over an event plumbing problem on my page. I have a single ASP.NET UserControl that monitors some browser-side events and raises them as UpdatePanel async-post-backs to the server. Let's call it EventPump. It includes some JavaScript and server-side controls to manage the events. It works great.

I have several other controls on the same page that don't know about each other but would like to subscribe to some of the events raised by the EventPump. Normally one control would subscribe to another's events by including that control in its markup and wiring the events. But in this case that would give me multiple instances of EventPump, which I don't want.

How can I have several UserControls subscribe to events of the common EventPump control?

like image 785
n8wrl Avatar asked Nov 13 '22 16:11

n8wrl


1 Answers

A few additional options I can think of:

  1. Code to interfaces, so the EventPump control implements IEventPump which has a various public events. The containing page implements IEventPumpContainer with one property called EventPump which allows all other user controls to register like so:

    ((IEventPumpContainer)Page).EventPump.MyEvent += MyEventHandler;
    
  2. If the page is aware of the controls that need to subscribe you could have it call appropriate methods on the controls when events fire. For example:

    EventPump.MyEvent += (s, e) => SomeControl.SomeMethod();
    
  3. Alternatively and arguably better is to make the events first class citizens and have an event dispatcher that can be used to subscribe to and raise events. For example:

    Events.Register<MyEvent>(e => TextBox.Text = "MyEvent Happened");
    ...
    Events.Raise(new MyEvent());
    
like image 169
MrBretticus Avatar answered Dec 05 '22 19:12

MrBretticus