{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
How does a namespace get registered in MS AJAX?
Summary
This article looks at how Microsoft AJAX library adds (‘simulates’) the namespace functionality. Understanding this not only lets you create namespaces in your client-side JavaScript code, but also helps you debug the client-side code effectively.
 
Table of Contents

The method registerNamespace

Code Listing 1. Complete Listing of the registerNamespace method

Root Namespaces

Code Listing 2. Parts of registerNamespace method that create root namespaces

Figure 1: Two root namespaces

Fully contained namespaces

Code Listing 3. Registering Sub-namespaces

Figure 2. Namespaces contained within Sys namespace

 

Most of the JavaScript code that’s out there is full of global variables. On a simple page with a little bit of JavaScript code, this would be fine. But, as more and more JavaScript is being injected onto a page (from ASP.NET, MS AJAX, third-party JS libraries, third-party custom controls with AJAX functionality), the possibility of name collisions becomes very real.

The method registerNamespace

MS AJAX provides a convenient way to declare a namespace and then associate whatever the classes you want with it. Obviously, the concept of namespace is not native to JavaScript (prior to 2.0). So, how does the namespace concept provided with MS AJAX work?

In MS AJAX, you would use the following statement to register a namespace:

Type.registerNamespace(‘AjaxControlToolkit’);

In the above statement:

Name of the namespace you are trying to register: AjaxControlToolkit

registerNamespace: the method that registers the namespace (remember, there is no concept of namespace in JavaScript. This method simulates that behavior)

Type: This is a global object created by the MS AJAX library. This object contains the methods that provide the object-oriented functionality: registerNamespace, registerClass, registerInterface, and registerEnum. This class is in the MicrosoftAjax.js file.

Now let’s see how the registerNamespace method in the Type class looks like.

Code Listing 1. Complete Listing of the registerNamespace method

Type.registerNamespace = function Type$registerNamespace(namespacePath) {
    /// <param name="namespacePath" type="String"></param>
    var e = Function._validateParams(arguments, [
        {name: "namespacePath", type: String}
    ]);
    if (e) throw e;

    if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument(’namespacePath’, Sys.Res.invalidNameSpace);
    var rootObject = window;
    var namespaceParts = namespacePath.split(’.’);

    for (var i = 0; i < namespaceParts.length; i++) {
        var currentPart = namespaceParts[i];
        var ns = rootObject[currentPart];
        if (ns && !ns.__namespace) {
            throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsObject, namespaceParts.splice(0, i + 1).join(’.’)));
        }
        if (!ns) {
            ns = rootObject[currentPart] = {};
            if (i === 0) {
                window.__rootNamespaces[window.__rootNamespaces.length] = ns;
            }
            ns.__namespace = true;
            ns.__typeName = namespaceParts.slice(0, i + 1).join(’.’);
            var parsedName;
            try {
                parsedName = eval(ns.__typeName);
            }
            catch(e) {
                parsedName = null;
            }
            if (parsedName !== ns) {
                delete rootObject[currentPart];
                throw Error.argument(’namespacePath’, Sys.Res.invalidNameSpace);
            }
            ns.getName = function ns$getName() {return this.__typeName;}
        }
        rootObject = ns;
    }
}

Root Namespaces

Now let’s take out the error checking type code from the above listing to see how exactly the root namespace functionality is being added.

Code Listing 2. Parts of registerNamespace method that create root namespaces

    var rootObject = window;
    var namespaceParts = namespacePath.split(’.’);

    for (var i = 0; i < namespaceParts.length; i++) {
        var currentPart = namespaceParts[i];
        var ns = rootObject[currentPart];


      if (!ns) {
            ns = rootObject[currentPart] = {};
            if (i === 0) {
                window.__rootNamespaces[window.__rootNamespaces.length] = ns;
            }
            ns.__namespace = true;
            ns.__typeName = namespaceParts.slice(0, i + 1).join(’.’);

If you are creating a root level namespace – just Sys or AjaxControlToolkit, not Sys.UI or AjaxControlToolkit.MyExt – then the code in Listing 2 has the most relevant parts.

Let’s say we are adding AjaxControlToolkit as a root namespace; meaning, we are NOT creating, for example, a namespace called Sys.AjaxControlToolkit. If we did that, the root namespace will by Sys and AjaxControlToolkit will be a namespace within that namespace.

MS AJAX creates an array of root-level namespaces called __rootNamespaces. That gets accomplished by the following statement:

window.__rootNamespaces[window.__rootNamespaces.length] = ns;

This new namespace is being added at the end of the array __rootNamespaces. This newly added object (added to window) needs be identified as a namespace. That is accomplished by adding a variable called __namespace.

ns.__namespace = true;

If you add AjaxControlToolkit to your web site, the page will have two root level namespaces: Sys and AjaxControlToolkit. The Sys namespace (and the classes and the namespaces within it) contains the primary MS AJAX functionality.

Figure 1: Two root namespaces

Figure 1: Two root namespaces

As you can see from Figure 1, the __rootNamespaces array has two slots in it. Each of them have the variables __namespace and __typeName. With __namespace set to true, the MS AJAX infrastructure knows this object is a namespace. And the __typeName variable is set to the name of the namespace – Sys and AjaxControlToolkit.

Fully contained namespaces

You would be just creating root level namespaces. You would also create namespaces within the namespaces. For example, the MS AJAX libraries have Sys as the root namespace. Then there are namespaces like Sys.UI, Sys.Net, etc. that contain UI and Net related classes.

Let’s see how are these namespaces added to the root namespaces.

Code Listing 3. Registering Sub-namespaces

    var rootObject = window;
    var namespaceParts = namespacePath.split(’.’);

    for (var i = 0; i < namespaceParts.length; i++) {
        var currentPart = namespaceParts[i];
        var ns = rootObject[currentPart];

        if (!ns) {
            ns = rootObject[currentPart] = {};


          }
            ns.__namespace = true;
            ns.__typeName = namespaceParts.slice(0, i + 1).join(’.’);


      }
        rootObject = ns;

The for loop in Listing 3 goes through the parts within the namespace – Sys.UI has two parts: Sys and UI. The second part of the namespace (UI) is added as member of the associative array. So, __rootNamespaces[0][‘UI’] would be where the Sys.UI resides.

Figure 2. Namespaces contained within Sys namespace

Figure 2. Namespaces contained within Sys namespace

As you can see in Figure 2, all the sub-namespaces of Sys (Application, Net, UI, WebForms, etc.) are now available from __rootNamespaces[0].

So, that’s how the namespaces and sub-namespaces are organized within the window DOM object. Your client-side JavaScript files could have a root namespace called ‘YourProduct’ and then additional namespaces called ‘YourProduct.UI’, ‘YourProduct.Services’, etc.

Bookmark and Share This

More Articles With Similar Tags
icon-ajax-to-existing-projects.jpg
Since JavaScript has been supported by every major web browser for a long time now, every decent-sized web site uses some JavaScript. Now that ASP.NET AJAX is available, you might want to refactor and start adding some of the functionality available in these libraries. This article goes through the initial refactoring steps.
icon-ajax-browser-detection.jpg
ASP.NET AJAX client side libraries provide a Sys.Browser class. This class along with objects like Sys.Browser.InternetExplorer can be used to detect the browser that the current page is running on. This article discusses the browser detection from the client side.
icon-ms-ajax-validation.jpg
Since JavaScript is a loosely-typed language, type checking is not done for you automatically. If you are writing library-type functions (those that would be used by other developers), it is very useful to validate the parameters. Here is how MS AJAX does the parameter validation.
icon-ajax-char-counting.jpg
It would be very useful to have counter right next to the textbox and increase that number as the user is typing into that textbox. Based on the lengths of the string entered into the textbox we could change the background of the textbox (white, yellow, red). This can be done in JavaScript (on MS AJAX) with relatively a few lines of client-side code.
icon-extender-class-hierarchy.jpg
This article looks at how a control written with MS AJAX gets initialized on the client side. Discusses the JavaScript methods from the client-side library that get called in the initialization of the control. The example used here is the creation of an instance an autocompleteextender control.
About  Contact  Privacy Policy  Site Map