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. It is by no means an equivalent set of functionality, but it does go a long way toward simplifying JavaScript coding tasks.
Basic support for removing whitespace is added to JavaScript strings with new methods. The trim method performs the equivalent of trimBegin 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 (Trim.aspx) demonstrates using the trim, trimStart, and trimEnd functions.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX Trim</title>
<script type="text/javascript">
function pageLoad(sender, args) {
var one = ' leading
var two = 'trailing whitespace ';
var three = ' leading and trailing whitespace ';
alert('.' +
alert(one); //the original string is not modified
alert('.' +
alert('.' +
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" ID="sm"/>
</div>
</form>
</body>
</html>
The trim methods are just shortcuts to what you can do with a regular expression. But 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.
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 (from Formatting.aspx) has examples of string formatting. The displayFavorites function injects a set of variables into a string. No format specifier is included. Then the {0:d3} format specifier is used to indicate that the number should be padded if it consists of fewer than three digits.
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Threading" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX String Formatting</title>
<script runat="server" language="C#">
protected override void OnLoad(EventArgs e) {
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture("de-DE");
}
</script>
<script type="text/javascript">
function pageLoad(sender, args) {
var d = new Date();
var message = String.localeFormat("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{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 runat="server" ID="sm" EnableScriptGlobalization="true" />
</div>
</form>
</body>
</html>
The result of using the various date formats is shown in the pop-up window in Figure 4-3.
The Array type is used heavily in JavaScript coding. It can be treated as both a stack and 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 (Arrays.aspx) 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. But 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, I am passing a reference to a function that simply displays the element of the array using the built-in alert method.
<%@ Page Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>ASP.NET AJAX Arrays</title> <script type="text/javascript"> function arrayMethod(element, index, array) { alert(element); } function pageLoad(sender, args) { var array = new Array(); Array.add(array, "Junta"); Array.add(array, "Lawn Boy"); if(Array.contains(array, "Junta")) { Array.clear(array); } array = Array. var items = ["Stash", "Hoist", "Tracking"]; Array.addRange(array, items); Array.insert(array, 1, "Lawn Boy"); for(var i = 0; i < array.length; i++) { alert(array[i]); } Array.forEach(array, arrayMethod); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager runat="server" ID="sm" EnableScriptGlobalization="true" /> </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. Providing this functionality as static methods avoids those problems. The type can also be used as associative arrays, 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 (Objects.aspx) illustrates using an object as an associative array.
<%@ Page Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Associative Objects</title>
<script type="text/javascript">
function pageLoad(sender, args) {
var releaseDates = new Object();
releaseDates["Junta"] = new Date("May 8, 1989");
releaseDates["Lawn Boy"] = new Date("September 21, 1990");
releaseDates["Picture of Nectar"] = new Date("February 18, 1992");
releaseDates["Rift"] = new Date("February 2, 1993");
for(var property in releaseDates) {
alert(property + " was released " + releaseDates[property]);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" ID="sm" EnableScriptGlobalization="true" />
</div>
</form>
</body>
</html>