Ying
Ying

Reputation: 1152

Javascript interaction between ASP.NET web controls

I have a UserControl A which contains

At runtime the placeholder will be populated with some UserControl B.

There are certain times which I need to trap the javascript onchange event in the dropdown to call a javacript function in B (to do a clientside update of B). What is a good design/practice for how to do this?

The naive way is to make the asp:dropdownlist a public member then send it into a public method of B:

// In controlling code
...
userControlB.Initialize(userControlA.TheDropDownList);
...


// In usercontrol B
public void Initialize(DropDownList dropdownFromA)
{
    dropdownFromA.Attributes.Add("onchange", "myBfunction()");
}

But something smells bad with this approach. I would like to keep A and B as loosely coupled as possible. Any better ideas?

Upvotes: 0

Views: 560

Answers (2)

JoshBerke
JoshBerke

Reputation: 67068

To keep them really decoupled you could introduce an observer pattern such as described here. I would have the drop down register it's own change event which would notify the observer that a change occured. Then if any other controls on the client are interested they will enlist to be notified when a specific observation is made.

Edit

Well you could name the variables based on a logical name for the observation, then you'd just check to make sure the observer exists before registering with it.

A different system I have seen used, would be more like an event dispatcher, essentially when you subscribe you provide a name for the event, then you fire you would include two arguments the name of the event, and the data for the event. In this model you would only have a single dispatcher on a page.

Upvotes: 3

Lazarus
Lazarus

Reputation: 43084

Within the DOM I'm fairly sure that all controls are accessible so making the dropdown public isn't really relevant, particularly as control a and control b are members of the same page and so are accessible to each other in your code-behind.

I'd think a more loosely coupled approach would be to have control B register it's method as an event listener on control a's change event. I'm not sure how much more loosely coupled you could make two controls where one depends on changes from another.

Upvotes: 0

Related Questions