Microsoft AJAX Library Tutorial: Classes and Namespaces

Exercise Explanations

This is a OOP with Microsoft AJAX Library exercise from Chapter 5 of Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

The Microsoft AJAX Library contains a special class named Type (which is an alias for JavaScript's Function constructor), which defines a set of properties and methods that provide typing and type-refl ection capability, and other common features required when building ASP.NET AJAX applications. Type provides these features:

As in typical .NET development, namespaces offer the means for avoiding type collision, and are used as containers for classes. They provide a simple yet efficient way to group common functionality implemented in classes in tree-like structures. It takes less effort to narrow our search when finding a class when guided by the namespaces at each step. Searching inside the current namespace is certainly easier than having to search in the global namespace that might contain hundreds of classes. In order to create a new namespace and to register it, we use the registerNamespace() static method of Type:

Type.registerNamespace("Samples");

Namespaces are registered as property objects of the JavaScript's window object. This means they become available to all the running scripts. Root namespaces like the one defined on the previous page are also registered in the __rootNamespaces property of the window object. This property is an array of all the registered root namespaces allowing us to declare nested namespaces that are registered as properties of their parent namespaces (rather than as properties of the window object). For example, we can declare the following nested namespace:

Type.registerNamespace ("Samples.Chapter5");

In this case, the Chapter5 namespace will be added as an Object property to the Samples entry in the __rootNamespaces array.

In the exercise that follows, we will build a class (Person) that exposes a single property (name) and a single event (change). The name property can be read or modified through the get_name() and set_name() accessor methods. As you know, it is possible to register several event handlers for the same event. To demonstrate this, we will register programmatically two event handlers for the change event. These functions will execute when the change event is fired, and we will see how our event handlers are notified. The following figure represents the Person class that you create in this exercise.

JavaScript Person Class Diagram

Implement the exercise step by step and find detailed explanations in our book, Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.