Prototype: Easing AJAX's Pain
by Bruce Perry
|
Pages: 1, 2, 3, 4
Objective View
The CO2Levels object definition appears in a different JavaScript file, aptly named co2.js. Figure 1-2 shows a UML class diagram describing the object.

Figure 1-2. UML class diagram
Here is the entire code for the CO2Levels object. The first line instantiates a new object, using syntax derived from Prototype. The levels local variable is an object, like an associative array, that links years with their CO2 levels. I have omitted most of the years for the sake of readability.
var CO2Levels=Class.create();
CO2Levels.prototype = {
/*
Source: http://cdiac.esd.ornl.gov/ftp/trends/co2/maunaloa.co2
Mauna Loa Observatory, Hawaii
*/
initialize: function(){
this.levels={ "1959":315.98,"1960":316.91,
"1961":317.65,"1962":318.45,
"2003":375.64,"2004":377.38};
this.levelsHash=$H(this.levels);
},
getYear: function(year){
if (! isNaN(year)) {
return this.levelsHash[year];
} else {
return 377;
}
},
keys: function(){
return this.levelsHash.keys();
},
values: function(){
return this.levelsHash.values();
},
inspect: function(){
alert( this.levelsHash.inspect());
},
add: function(year,level){
var tmp = new Object();
tmp[year] = level;
this.levelsHash=this.levelsHash.merge(tmp);
}
}
Creating Prototype Objects
Using the Class.create() method in Prototype returns a JavaScript object that automatically provides new instances of this object with an initialize() method. This is similar to a constructor method, such as in Java. The initialize() method will be called each time the code creates a new CO2Levels object. The rest of the code defines the prototype, or blueprint, for this CO2Levels object, including the behavior for its initialize() method. What does initialize() do? It creates a local variable called levels, which refers to an object that holds all of the data: the CO2 levels associated with their years. The code then converts this object to a Prototype Hash object, to provide more functionality for the object (such as the ability to view the object contents and dynamically add new data).
this.levelsHash=$H(this.levels);
Prototype Hash Object
There's that syntax again: $H(). This function takes a JavaScript object as its parameter and returns Prototype's Hash object. Similar to hash table structures in other languages, the Hash has an associative array structure, along with with several methods that are designed to manipulate its data, as well as add new data to the Hash.
For example, the Hash.keys() method returns an array of all of the Hash's keys (such as all of the years in our data). The values() method returns an array of values (the CO2 levels). The merge() method adds new keys and values to the Hash.