views:

440

answers:

3

I'm working on a project where a central class (the subject), will contain alot of data. There will be an aspx page that displays this data, using .net ajax. When the subject is updated from any page, I want all the open pages to update. I will be using the observer pattern for this. THe question is, do I make the actual aspx page the observer, or is there a better way to do this?

+1  A: 

I'm not familiar with the observer pattern, but the only way you have to do this is to place a javascript endless loop on page load that every X seconds invokes an AJAX method on the server to check for updates.

Sergio
+6  A: 

An observer pattern doesn't make sense in this case.

The web (and ASP.NET) works by way of requests (e.g. from a web browser) and responses (e.g. from a web server).

An observer pattern requires that the subject (e.g. a web server) maintains references to it's observers (e.g. web browsers) and pushes notification updates to them. Clearly this is not applicable to a web browser-web server scenario.

I agree with Sergio that the best method is probably to make your clients (web browsers) periodically check for updates from the resource (web server). The neatest method of doing this would be an AJAX call.

A good example is Gmail, new messages appear in the inbox soon after they are received on the server without the user having to make an explicit request. This is done by AJAX calls which periodically check the Gmail server for new messages.

AdamRalph
+2  A: 

Sergio is right, and so are you to an extent. The easiest way to implement this through Asp.Net AJAX is using an AJAX timer control, but you certainly don't want to duplicate that across all your pages. A better approach would be to wrap that functionality up into a Master page, or even create a base page that derives from Page.

Check out the MSDN page on the Timer Control, and a decent video tutorial as well.

As a side note on design, I wouldn't necessarily put the actual observer code inside your code behind however. Rather, you want to forward those events on to some underlying model. The idea is that your Code Behind is responsible only for UI related stuff and the logic to make that happen. Essentially the V in MVP/MVP.

Also, I am not sure how well the "actual" observer pattern applies in a web context considering you are talking about a single HTTP Reponse/Request cycle with no real state.

Josh