Utility functions
Many JavaScript frameworks come with a large number of utility functions that make it easier to develop applications using JavaScript. There's too much to add to this article, so I'll discuss one of the more compelling functions in most frameworks.
If you've ever worked with JavaScript arrays, you're probably familiar with using loops to iterate over an array and manipulate its values. For example, consider the code in Listing 2:
Listing 2: The traditional way to iterate over a JavaScript array
var fruit = ['apple', 'banana', 'orange'];
for(var i = 0; i < fruit.length; i++) {
alert(fruit[i]);
}
The code in Listing 2 is correct, but it's a bit cumbersome. Most JavaScript frameworks include the each function, which calls a specific function for each element in the array. Using MooTools, the same operations in Listing 2 can be accomplished using the code in Listing 3.
Listing 3: Using MooTools’ each function
['apple', 'banana', 'orange'].each(function(item) {
alert(item);
});
Listing 3 is syntactically identical to Prototype and jQuery, with slight differences between YUI and ExtJS. However, the syntax is different across different frameworks when applied to hashes or objects. For example, in MooTools, you can use the code in the following listing:
Listing 4: Using MooTools’ each function on individual objects of key/value pairs
var hash = new Hash({name: "Joe Lennon", email: " [email protected] "});
hash.each(function(value, key) {
alert(key + ": " + value);
});
However, using the Prototype library, this looks just like the code in Listing 5:
Listing 5: Using Prototype’s each function on individual objects of key/value pairs
var hash = $H({name: "Joe Lennon", email: " [email protected] "});
hash.each(function(pair) {
alert(pair.key + ": " + pair.value);
});
Each framework contains many more practical functions, usually divided into String function, Number function, Array function, Hash function, Date function, etc. To learn more, consult the API manual of the relevant JavaScript framework.
Reprint address: http://www.denisdeng.com/?p=716
Original address: http://www.ibm.com/developerworks/web/library/wa-jsframeworks/index.html