Mike Ormond's Blog

Musings on mobile development and Windows Phone 7 in particular.

Building ASP.NET AJAX Controls (Pt 5 - The bits I didn't get to in the last post)

Building ASP.NET AJAX Controls (Pt 5 - The bits I didn't get to in the last post)

  • Comments 1

Links to the other posts in this series 

NB I introduced an error in Pt 3 which I have since corrected (near the bottom beneath the aspx listing)

So we were left with two outstanding questions after Pt 4:

  • Can I expose my own events on my component?
  • What about those property change notifications you mentioned?

Exposing your own events is pretty straightforward. There is an events property on your component (see Pt 2) that should be used to maintain the list of event handlers mapped to your component's events. What you need to do is provide methods for adding and removing handlers and most likely a helper method to raise events. Again, by convention, the methods to add / remove handlers are called add_eventName() and remove_eventName(). Say we wanted to add an event that could be used to notify when the position of the map in our VEMapControl component changed:

Picture1

The helper method to raise events might be something like:

Picture2

This calls the getHandler() method on the events property which returns a method that when invoked will call all the handlers for the specified event. Pretty clever eh? We then just check if it's null (in which case no handlers to call). If it's not null, check if we were passed any eventArgs and if not, set them to empty then call that magic method. We'd then modify our setters for lat and lon to raise the event:

Picture3

Of course in this instance a more appropriate mechanism to use might be property change notifications. In Pt2 I mentioned that components implement INotifyPropertyChange and have a raisePropertyChanged() method. How convenient!

Picture4

We can then hook up to the property change notification by modifying our $create call to hook a handler to the propertyChanged event and, in the handler, test which property has actually changed:

function pageInit() {
    $create(    ServerControls.VEMapControl,
                        { 'lat' : 52.0, 'lon' : -1.0 },
                        { propertyChanged: onPropertyChanged },
                        {},
                        $get("div1"))        
}

function onPropertyChanged(sender, args) {
    if (args.get_propertyName() == 'lat') {
        alert('The latitude has been changed');
    }
}

Okay, I think we've covered everything we need to before we start talking about taking these puppies to the server side. What do we need to do to create server controls that emit client side components, behaviors and controls. Tune in next time folks...