The observer pattern in MS AJAX – part IV

In this last post on the observer pattern, we’ll be seeing one last approach which you can follow to apply this pattern in your pages. I can tell you right now that you won’t be using this much in real world (will it ever be used?). However, since some AJAX controls use it internally, I thought it would be a good idea to at least mention it here in my blog.

As we’ve seen, the recommended approach for using  the Sys.Observer helper relies on passing an object to the makeObservable method. As we’ve seen, this leads to the change of the API of the object. Unfortunately, that might not be possible when the observable object already has a method with the same name as one of the “observable methods” (if that happens, you’ll end up with an exception).

However, not all is lost! You can still end up getting change notifications, but that means using the “static” helper methods directly. Let’s start with a simple student object:

var student = {
    name: "Luis",
    address: "Fx"

As you can see, student isn’t an observable object (nor does it expose the necessary propertyChanged event either). However,we can still be notified about changes in its state. The first thing we need to do is to show interest in getting those notifications:

Sys.Observer.addPropertyChanged(student,function(sender, e) {

Instead of using an “instance” method, we rely on the “static” method introduced by the Sys.Observer helper object to hook up the event to an anonymous function. As you might have guessed by now, changes can’t be done by changing the properties of the student object directly. If you’re thinking that there’s a static method that achieves the same thing as the setValue method (which is added to an observable object through the makeObservable call), then you’re absolutely right.

Here’s the code you need to get notifications on state change:

Sys.Observer.setValue(student, "name", "luis");

Once again, we end up relying on the “static” setValue method, introduced by the Sys.Observer helper. This is only possible because the methods you’d normally add to an observable object end up delegating all the work to these static methods.

This is an approach which I don’t really recommend, but it’s possible, so you’re free to use it whenever you want. Stay tuned for more on MS AJAX.


~ by Luis Abreu on October 6, 2009.

One Response to “The observer pattern in MS AJAX – part IV”

  1. You also don”t want to change an object that you don”t own, as it may have unintended consequences.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: