4.3. Base Class Library

The AJAX Library takes a familiar set of features from the base class library of the .NET Framework and brings it to JavaScript in the browser for you to use in building your applications. It is by no means an equivalent set of functionality as what the base class library offers, but it does go a long way toward simplifying your JavaScript coding tasks.

4.3.1. The String Class

Basic support for removing whitespace is added to JavaScript strings with new methods. The trim() method performs the equivalent of trimStart() and trimEnd(). The instance of the string is not modified by the trim calls. Instead, a copy of the string is returned with the requested change. Listing 4-14 demonstrates using the trim(), trimStart(), and trimEnd() functions.

Example 4-14. Working with the String class
<%@ Page Language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Using Trim Functions</title>

    <script type="text/javascript">

        function pageLoad(sender, args) {

            var one = ' leading whitespace';
            var two = 'trailing whitespace ';
            var three = ' leading and trailing whitespace ';

            alert('.' + one.trimStart() + '.'),
            alert(one);  //the original string is not modified
            alert('.' + two.trimEnd() + '.'),
            alert('.' + three.trim() + '.'),

        }

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

The trim methods are just shortcuts to what you can do with a regular expression. However, they do provide a certain familiarity. This holds true of the beginsWith() and endsWith() methods, too. You could write the functionality easily yourself but having method names that are clear and easy to use makes the transition in and out of JavaScript easier.

4.3.2. Dates and Numbers

The complexities of formatting really come into play when dealing with dates and numbers. The ASP.NET AJAX Library adds format() and localeFormat() methods to the string, date, and number objects. The format and methods are key for effectively controlling output. Instead of concatenating pieces of text with variables, you can call String.format() to have variables put into placeholders of a single string. The placeholders in the string are a pair of curly braces containing a variable number and optional format string. The number indicates which of the parameters following the string will be used. A variety of format strings like those available in the .NET Framework allow you to easily control how numbers are represented.

The localeFormat() goes further by respecting culture-specific settings in formatting dates and numbers. You can establish the culture that the user prefers and know that your data is being formatted and displayed correctly in the browser.

Listing 4-15 illustrates some examples of string formatting.

Example 4-15. Working with dates
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Threading"%>
<%@ Import Namespace="System.Globalization"%>

<script runat="server">

       protected void Page_Load(object sender, EventArgs e)
       {
           Thread.CurrentThread.CurrentCulture =
              CultureInfo.CreateSpecificCulture("fi-FI");
       }

    </script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dates and time</title>

    <script type="text/javascript">

        function pageLoad(sender, args) {

            var d = new Date();
            var message =
                String.localeFormat("{0}
{1}
{2}
{3}
{4}
{5}
{6}
{7}",
                d.format("d"),
                d.format("D"),
                d.format("t"),
                d.format("T"),
                d.format("F"),
                d.format("M"),
                d.format("s"),
                d.format("Y") );
            alert(message);

        }

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"
         EnableScriptGlobalization="true">

</asp:ScriptManager>
    </div>
    </form>
</body>
</html>

The result of using the various date formats is shown in the pop-up window in Figure 4-3.

Figure 4-3. Figure 4-3

4.3.3. Arrays

The Array type is used heavily in JavaScript coding. It can be treated as a stack and as a queue, and it allows for sparse arrays. Many basic data structures can use the Array as the underlying building storage mechanism. The AJAX Library adds a set of static functions to the Array type that improve its usability and make it more familiar. During a preview release of the AJAX Extensions, the additional functionality was added to the Array prototype. After careful consideration, this approach was changed in order to avoid incompatibilities with other JavaScript libraries.

If you are already used to the JavaScript Array methods, you may recognize that the new methods are wrappers to use the method names from the .NET Framework base class library. You also get the benefit of some very detailed analysis into the performance characteristics of working with arrays. For example, adding a single element to an array is best accomplished by using an indexer with assignment rather than calling Push(). The AJAX Library provides the Array.add() method to expose a less awkward method.

array[array.length] = something; //is more efficient than
array.Push(something);

Listing 4-16 demonstrates using the additional Array methods to work with an Array. The add(), contains(), and clear() methods do what you would expect, but the static methods on the Array type take a little getting used to. The parse() method takes a string that looks like an array listing and parses it for the individual elements. However, the forEach() method is most interesting. You pass the array and a callback method, and the forEach() method is then automatically called for each element of the array. In this case, you need to pass a reference to a function that simply displays the element of the array using the built-in alert method.

Example 4-16. Working with arrays
<%@ Page Language="C#" Debug="true" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Arrays</title>

    <script type="text/javascript">

        function pageLoad(sender, args) {

            var array = new Array();
            Array.add(array, "Lost Highway");
            Array.add(array, "Have a Nice Day");

            if(Array.contains(array, "Lost Highway")) {
                Array.clear(array);
            }
            array = Array.parse("['Lost Highway', 'Slippery When Wet']");

            var items = ["New Jersey", "Cross Road", "One Wild Night"];
            Array.addRange(array, items);
            Array.insert(array, 1, "Have a Nice Day");

            for(var i = 0; i < array.length; i++) {
                alert(array[i]);
            }

            Array.forEach(array, arrayMethod);

        }

        function arrayMethod(element, index, array) {
            alert(element);
        }


    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

The debate around extending the Array prototype centers on problems that can be encountered when iterating over the members of the type as you cannot extend the type as you are iterating through it. Providing this functionality as static methods avoids those problems. The type can also be used as an associative array, but the generally accepted pattern is to use the object itself for creating associative arrays. For compatibility, arrays are better suited for collections of objects or numeric index associations.

Listing 4-17 illustrates using an object as an associative array.

Example 4-17. Working with associative arrays
<%@ Page Language="C#" Debug="true" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Arrays</title>

    <script type="text/javascript">

        function pageLoad(sender, args) {

            var releaseDates = new Object();
            releaseDates["Lost Highway"] = new Date("June 19, 2007");
            releaseDates["Have a Nice Day"] = new Date("September 20, 2005");
            releaseDates["Slippery When Wet"] = new Date("August 1, 1986");
            releaseDates["Cross Road"] = new Date("October 18, 1994");

            for(var property in releaseDates) {
                alert(property + " was released " + releaseDates[property]);
            }

        }

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

Arrays in JavaScript have methods similar to those presented through the .NET Framework's Array type. Some possible methods are presented here.

The add() method allows you to add a single item to the array:

var albums = ['Lost Highway', 'Cross Road'];
Array.add(albums, 'Have a Nice Day'),

for(var i = 0; i<albums.length; i++)
{
   alert(albums[i]);
}

The addRange() method allows you to add ranges of items to the array:

var albums1 = ['Lost Highway', 'Cross Road'];
var albums2 = ['Have a Nice Day', 'Slippery When Wet'];
Array.addRange(albums1, albums2);

for(var i = 0; i<albums1.length; i++)
{
   alert(albums1[i]);
}

In this case, everything is added to the albums1 instance and running this code, results in four alerts from albums1 — one for each album.

You will also find a clear() method. This will do what it says — clear out your array object.

var albums = ['Lost Highway', 'Cross Road'];
Array.add(albums, 'Have a Nice Day'),

for(var i = 0; i<albums.length; i++)
{
   alert(albums[i]);
}

Array.clear(albums);

alert(albums.length);

In this case, the first set of three alerts shows the name of each album found in the collection. The fourth alert, comes after the array is cleared using the clear() method and therefore shows a length value of 0.

The clone() method copies the values of your array to another array instance. This means that if you change the value in the array you copied from, the copy still retains its original values. An example of using the clone() method is presented here:

var albums = ['Lost Highway', 'Cross Road'];
var albumsCopy = Array.clone(albums);

albums[1] = "DELETED";

alert(albums[0] + "
" + albums[1]);
alert(albumsCopy[0] + "
" + albumsCopy[1]);

This produces a set of alerts as shown in Figure 4-4.

Figure 4-4. Figure 4-4

The contains() method returns a Boolean value that specifies whether the item you were looking for was found in the array:

var albums = ['Lost Highway', 'Cross Road'];

alert(Array.contains(albums, "Lost Highway"));
alert(Array.contains(albums, "Lost"));

In this case, the first alert is true because the item Lost Highway will be found, but the word Lost returns false because partial matches are not allowed.

The push() and pop() methods allow you to enqueue and dequeue items on the stack:

var anArray = [];
anArray.push(1);
anArray.push(2);
anArray.push(3);

alert(anArray.pop());
alert(anArray.pop());
alert(anArray.pop());

In this case, items are put onto the stack of the array in the order of 1, 2, 3 and then they are dequeued from the stack in the opposite order of 3, 2, and 1.

Just as you can add items to the array, you can remove items using the Array.remove() and Array.removeAt() methods.

4.3.4. Booleans

Booleans are true/false or 0/1 values, also known as a bit. You will find a Boolean type within the ASP.NET AJAX Framework that allows you to use true or false string values instead of the standard 0 or 1 values for Booleans. To accomplish this task, you will need to use the parse() method on the Boolean type.

var myBoolean = "true";
alert(Boolean.parse(myBoolean));

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset