Create a cracker object: function crackerid, name, desc, broken, crackimg {}, to set up the cracker and accept parameters for its initial values.. Create a nested function in the objec
Trang 1Lab 10:
Custom Objects
TIP: Because this lab includes a great deal of typed code, we’ve tried to make it
simpler for you You will find all the code in AnimalCrackers.html and
AnimalCrackers.js in the same directory as the sample project Also, the
images you’ll need are: butterfly.gif, b_butterfly.gif, elephant.gif,
b_elephant.gif, puppy.gif, b_puppy.gif, and CrackerBox.gif While the lab
can be constructed without the images, it is better to use them to see how the data translates to a visual interface To avoid typing the code, you can cut/paste it from the source files instead
Trang 2Lab 10 Overview
Lab 10 Overview
In this lab you will learn how organizing data into custom objects makes it easy to manipulate, display, and handle provided data
To complete this lab, you will need to work through two exercises:
Crackers, Photos, and their Methods
Build a User Interface Each exercise includes an “Objective” section that describes the purpose of the exercise You are encouraged to try to complete the exercise from the
information given in the Objective section If you require more information to complete the exercise, the Objective section is followed by detailed step-by- step instructions
NOTE Each exercise has its own initCrackers function to launch the
exercise from the <body onload=’’> event in AnimalCrackers.html The first exercise launches with initCrackers() and the second exercise launches with initCrackersEx2() To test the completed exercises, be sure to make the appropriate change to the onload attribute
Trang 3Crackers, Photos, and their Methods
Otherwise, define the function outside of the object definition to make
it a global function, so that you can call it wherever it is needed
Broken crackers have a different image than complete crackers They
have the same base image name, but have the prefix b_ at the
beginning of the filename
Step-by-Step Instructions
1 Open the AnimalCrackers.js file, or create a new one if you are feeling adventurous The AnimalCrackers.html file sets up the interface for you, and looks for the code in the AnimalCrackers.js file For this entire lab, it
is important to place all the files within the same directory, including the images Otherwise you will need to update any references to the image files within the XHTML and JavaScript code to reflect the correct path to the files
2 Create a cracker object: function cracker(id, name, desc, broken,
crackimg) {}, to set up the cracker and accept parameters for its initial
values Next, initialize the parameters using the this.<parametername> =
<passed in parameter name> syntax to set the values for the cracker’s id,
name, description, its boolean indicator, broken, and an image file Also,
add two method definitions: this.getType and this.show.with default values of “unknown” for both methods
Trang 4Crackers, Photos, and their Methods
function cracker(id, name, desc, broken, crackimg) { this.id = id;
this.name = name || "unknown";
this.description = desc || "unknown";
this.broken = broken || false;
this.img = crackimg;
this.getType = getType || "unknown";
this.show = showCracker || "unknown";
}
3 Next, you must define the methods that were assigned to the getType and
showCracker methods in Step 2 Create a nested function in the object
called getType(), which will have only one statement: return
this.img.type; that returns the type of image that the cracker has The
cracker image object itself will be defined in a later step
function cracker(id, name, desc, broken, crackimg) { this.id = id;
this.name = name || "unknown";
this.description = desc || "unknown";
this.broken = broken || false;
this.img = crackimg;
this.getType = getType || "unknown";
this.show = showCracker || "unknown";
function getType() { return this.img.type;
}
}
4 Now, add showCracker() as a nested function When
crackerobject.show() is called, this is the function that executes The first
statement in the function should define the returned string: var txt =
“Animal Cracker ” + this.id + “\n”; The next line simply adds a dashed
line using the statement txt += “ -\n”; , to provide a
visual separation of the information On the next line, add a statement to
display the object’s name: txt += “Name: ” + this.name + “\n”; and its description: txt += “Description: ” + this.description + “\n”;, followed
by statements to display the object’s type, txt += “Type: ” +
Trang 5this.getType() + “\n”;, and broken boolean value, txt += “Broken: ” + this.broken + “\n”; You will also want to append the information
returned from the image object to the txt variable by adding txt +=
“\n\n\n\n” + this.img.show(); Again, the cracker image object will be
defined in a later step Finally, return the txt object using th estatement
return txt;
function getType() { return this.img.type;
}
function showCracker() { var txt = "Animal Cracker " + this.id + "\n"; txt += " -\n";
txt += "Name: " + this.name + "\n";
txt += "Description: " + this.description + "\n"; txt += "Type: " + this.getType() + "\n";
= showImg;
function crackerimg(src, auth, type) { this.src = src || "";
this.author = auth || "unknown";
this.type = type || "unknown";
this.show = showImg;
}
6 Create the crackerimg object’s internal show method with the statement
function showImg() {} Create the first string for the message var txt =
“Image Details:\n”;, and add a visual separator line with the statement txt
Trang 6Crackers, Photos, and their Methods
information about the image file, by appending cracker image src, author and type values to the txt string Finally, return the txt string with the statement return txt;
function crackerimg(src, auth, type) { this.src = src || "";
this.author = auth || "unknown";
this.type = type || "unknown";
this.show = showImg;
function showImg() { var txt = "Image Details:\n";
var testcrackerimg = new crackerimg("elephant.gif", "big elephant",
"myself", "Elephant Cracker"); Now create a new cracker called testcracker, using the statement var testcracker = new cracker(123,
"Cracker", "A tasty test", true, testcrackerimg); Finally, add a line to
show the user information about the cracker: alert(testcracker.show());
function initCrackers() { var testcrackerimg = new crackerimg("elephant.gif", "myself", "Elephant Cracker");
var testcracker = new cracker(123, "Cracker", "A tasty test", true, testcrackerimg);
alert(testcracker.show());
}
Trang 78 Open the AnimalCrackers.html file and add an onload event handler to the <body> tag that calls the initCrackers() method, and sets the page’s background color to #FFFFFF
<body onload="initCrackers()" bgcolor="#FFFFFF">
9 Open and test AnimalCrackers.html When the page loads, you should
get an alert box like the one in Figure 2, with the test crackers information The page that comes up with the cracker box and the elephants will be completed in the next exercise
Figure 2 The Opera 7 alert box with test cracker information
Trang 8Build a User Interface
Build a User Interface
Remember to keep code refactored for easy maintenance
In this exercise, the cracker’s id is obtained from a parameter of the
img objects on the html page called aindex This can be 0, 1, or 2
depending on the slot
The broken version of the image is the same filename, but with a “b_” attached to the front: “elephant.gif” and “b_elephant.gif”
Step-by-Step Instructions
1 Create a new init function for this exercise called initCrackersEx2() In
AnimalCrackers.html change the onload attribute in the <body> tag to
“initCrackersEx2()”
<body onload="initCrackersEx2()" bgcolor="#FFFFFF">
2 Return to your work from the previous example Add a global variable (outside of all other function or object definitions) to the file with the
statement var gTresCrackers = new Array(); to hold three random
crackers
<! //Global Cracker Container
var gTresCrackers = new Array();
Trang 93 Within the new initCrackersEx2 function, reset
gTresCrackers(„gTresCrackers = new Array();‟ ) to ensure that a new
array is created Following that statement, copy and paste the following arrays that provide lists of names, descriptions, and image information, which will be randomly selected when the exercise executes
//Reset gTresCrackers gTresCrackers = new Array();
//Options for random cracker generation
var gNames = new Array("Frank", "Rudolph", "Poopiekins", "Yellow", "Akim", "Ralphy", "Poomba", "Royale with Cheese", "Rowdy Roddy", "Hulk");
var gDesc = new Array("Reliable Cookie.", "Fun to chomp on.", "allright ", "Crumbly goodness", "Sensational taste value!", "A bit soggy.", "Best cookie in all of the world", "Fabulous texture!", "Down-right stale!",
"How old is this box?", "Allright, who poured milk in the box already?"); var gImgs = new Array(
"elephant.gif|David Fitzhenry|Enormous Elephant", "butterfly.gif|Carolyn Lail Fitzhenry|Beautiful Butterfly", "puppy.gif|Noah Kriegel|Perky Puppy");
4 Under the new Arrays, create a new for loop that will go through three
iterations: for (c = 0; c < 3; c++) {} Within the body of the loop, define a new cracker using the statement var newcracker = new cracker(); and a new image with the statement var crackerpic = new crackerimg();
for (c = 0; c < 3; c++) { var newcracker = new cracker();
var crackerpic = new crackerimg();
}
Trang 10Build a User Interface
5 Set up two new utility functions, called setCrackerProperties(crkr,
loopid) {} and setImageProperties(crkrimg, crck) {}, that are outside of
the loop, but within the initCrackersEx2() function In the for loop, under the newcracker and crackerpic variables, add the following statements
setCrackerProperties(newcracker, c); and setImageProperties(crackerpic, newcracker); to call the functions
for (c = 0; c < 3; c++) { var newcracker = new cracker();
var crackerpic = new crackerimg();
6 Create a simple function, rand(num) {}, outside of the loop that accepts a
numeric value parameter and returns a random number using the statement
return Math.floor(Math.random() * num) within the function
function setImageProperties(crkrimg, crkr) { }
function rand(num) { return Math.floor(Math.random() * num);
}
7 Go to the setCrackerProperties function, and add code to set the properties
for the cracker using the statements crkr.id = loopid;, crkr.name =
gNames[rand(gNames.length)];, crkr.description = gDesc[rand(gDesc.length)];, and crkr.broken = (rand(2) == 1) ? true : false; This code will generate a cracker with properties selected randomly
from the options that have been created in the gNames and gDesc arrays
Trang 11function setCrackerProperties(crkr, loopid) { crkr.id = loopid;
crkr.name = gNames[rand(gNames.length)];
crkr.description = gDesc[rand(gDesc.length)]; crkr.broken = (rand(2) == 1) ? true : false;
}
8 In the setImageProperties()function, create a new array called apic to hold
the separate name, author, and description string values from a randomly
selected gImg Use the split() function to separate the name, author and description strings based on the “|” (pipe) character
function setImageProperties(crkrimg, crkr) { var apic = gImgs[rand(gImgs.length)].split("|");
crkrimg.src = apic[0];
if (crkr.broken) {
crkrimg.src = "b_" + apic[0];
} }
10 Finally, set the author value to index one of apic, and the type to index two
of apic
Trang 12Build a User Interface
function setImageProperties(crkrimg, crkr) { var apic = gImgs[rand(gImgs.length)].split("|");
crkrimg.src = apic[0];
if (crkr.broken) { crkrimg.src = "b_" + apic[0];
}
crkrimg.author = apic[1];
crkrimg.type = apic[2];
}
11 Return to the code in the for loop, and after the call to
setImageProperties(), add a line to set the newcracker’s image property, img, to crackerpic with the statement newcracker.img = crackerpic;
Then, on the next line, add a statement to push the completed newcracker
object into the global cracker array: gTresCrackers.push(newcracker)
for (c = 0; c < 3; c++) { var newcracker = new cracker();
var crackerpic = new crackerimg();
properties First create a new function, packImageElements() directly under the rand(num) function that you created in Step 6 Create an array
of the image elements that are located on the AnimalCrackers.html page, with the statement elemnts = new Array(document.frm.cracker0,
document.frm.cracker1, document.form.cracker2);
Trang 13function packImageElements() { var elemnts = new Array(document.frm.cracker0, document.frm.cracker1, document.frm.cracker2);
}
13 Each <img> tag in the XHTML has an aindex property associated with it,
to represent its cracker’s position in the global array, gTresCrackers Create a for loop under the elemnts declaration that will perform three iterations, using the statement for (f = 0; f < 3; f++) On the next line, set the src property of the current image in the array by adding the statement
elemnts[f].src = gTresCrackers[f].img.src Finally, set the image’s
aindex property to the current count with the statement elemnts[f].aindex
= f;
function packImageElements() { var elemnts = new Array(document.frm.cracker0, document.frm.cracker1, document.frm.cracker2);
for (f = 0; f < 3; f++).{
elemnts[f].src = gTresCrackers[f].img.src; elemnts[f].aindex = f;
}
}
14 Go back to the line after the for loop in the initCrackersEx2() function and call the packImageElements() function
Trang 14Build a User Interface
for (c = 0; c < 3; c++) { var newcracker = new cracker();
var crackerpic = new crackerimg();
executes, the image must pass in a reference to itself, which your code can use
to get the information needed to display that cracker’s properties
15 Create the selectedCracker(crckr) function outside of all the other functions, preferably at the end of AnimalCrackers.js The only line in
this function will generate an alert that displays the selected cracker’s information, using the statement
alert(gTresCrackers[crckr.aindex].show());
function selectedCracker(crckr) { alert(gTresCrackers[crckr.aindex].show());
}
16 Test the application Once it’s running, you should be able to randomly set
the crackers with the Get More Animal Crackers! button, and then click
on each cracker to see its information In addition, notice that if the selected cracker is broken, the program will display the broken cracker image, as in shown in Figure 3 If the selected cracker is not broken, the program will display the unbroken image, as shown in Figure 4