Creating Custom Prototype Objects


For the majority of small projects, using Flash's built-in objects is more than sufficient. Occasionally though, especially with larger projects, you might need to create custom prototype objects. Why would you need to do this? You might be working with information that lends itself very nicely to being treated as an object. For example, say you need to develop a check-in, check-out system for your local library. What does a library have in abundance ? Books, of course. You could create a Book object; Flash doesn't have one of those. Each book has properties, such as a title, an author, a year of publication, and so on. But what about methods? What kinds of methods would a book have? Well, if you need to check a book in or out, you would need a method to handle that. Any time you are dealing with a collection of related information, you should be thinking about how that information could be grouped in an object.

Unlike with class-based OOP languages, in ActionScript there is no command that explicitly says "the code beneath me defines a blueprint." In ActionScript, you simply build the various parts of the object and then tie them together at the end.

What are the parts you need to build? First you need to decide what properties your object should have. Remember that properties are used just to describe an object. Next you have to figure out what your object is actually going to do; that is, you need to create methods to control your object's behavior.

In the subsequent exercises, you are going to go through the creation process for a custom Book prototype object. Each Book object will be able to hold all the information about a book. In addition, the object will check the book out, check the book in, and retire the book.

Exercise 14.2 Intializing the Basic Properties

The first method you need to create is a constructor method that initializes a new Book object. In this case, when you initialize a new Book object, you need to set up a few variables . Notice that the constructor method has the same name as the type of object you're creating.You give the constructor method and the object you want to create the same name so that you know what type of object the constructor is actually creating. It wouldn't make any sense to give your constructor a name of Dog if it's going to be used to create book objects (unless, of course, you're really trying to drive someone nuts).

  1. Create a new file. Save it as book.fla.

  2. Select frame 1 and launch the Actions panel.

  3. To initialize the new book object, enter the following code:

     // Book Object  //                                        // Initialize the Book Object  function Book(author, title, available){     this.author = author;      this.title = title;      this.available = available;      this.retired = false;  } 
  4. Save your file.

That wasn't so bad. It initialized the basic properties of the Book object for you. Now you need to create the other methods for this object.

Exercise 14.3 Creating the checkOut Method

The next method checks the book out for you. If the book is available for checkout, the method returns a Boolean true; otherwise , it returns a Boolean false. Notice that the name of this function has this naming scheme: the name of the class, an underscore , and then the name of the method. This naming scheme is not necessary, but it is used so that the code is easier to understand.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Beginning on the new line, add the following code:

     // Check the book out  function Book_checkOut(){     If (this.available == true && !this.retired){         trace("You checked out " + this.title);          this.available = false;          return(true);      }else{         trace("I'm sorry, you can't check out " + this.title + ".          It's already checked out.");          return (false);      }  } 
  3. Check your syntax and save your file. Save early, save often. It's a good thing.

What does this code do for you? You're planning to check out a book. The first thing the code does is verify whether the book is available. For a book to be available, it must be not checked out (available = false) and it can't be retired (retired = true).

Note

The ==, &&, !, and + operators get used in this block of code. These might be new to you. The equality operator (==) tests two expressions for equality. It does not make any value assignments. If the two expressions are equal, it returns a value of true. If the expressions are not equal, it returns a value of false. The && operator is known as the " short-circuit and." It tests the expression on the left side first. If that expression is true, && tests the expression on the right side. If both expressions are true, a value of true is returned. If either expression is false, a value of false is returned. The !, or logical NOT operator, inverts the value of an expression. Thus, if a book has been retired, this.retired would have a value of true. Inverting the value sets it to false; thus, you get kicked out of the if statement. A little funky, yes, but think through it a couple times. The + is easy. It's used to concatenate strings of information. If the book you are checking out is The Hunt for Red October , the trace action prints "You checked out The Hunt for Red October" in the Output window.


If the value of available is equivalent to true and retired is not true, you can check the book out. If you check the book out, you need to change the value of available to false. Finally, if the book is available for checkout, the function returns a value of true. Otherwise, it returns a value of false.

You'll notice that there are a couple trace actions in this function as well. These give you visual confirmation in the Output window that your code is working as expected.

Exercise 14.4 Creating the checkIn Method

Next you need to define the checkIn method for your object. Not surprisingly, this looks very similar to the checkOut method.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Beginning on the new line, add the following code:

     // Check the book in  function Book_checkIn(){     If (this.available == false){         trace("Thank you for returning " + this.title);          this.available = true;          return(true);      }else{         trace("You can't check " + this.title + "in. It hasn't          been checked out yet.");          return (false);      }  } 
  3. Check your syntax and save your file.

This time, you are planning to return a book you have previously checked out. The first thing the code does is verify whether the book has actually been checked out. If the value of available is equivalent to false, you can check the book back in. You don't have to worry about whether the book has been retired. A book can't be retired until it has been checked back in. If you check the book in, you need to change the value of available to true so that someone else can check it out. If the book is available for checkout, the function returns a value of true. Otherwise, it returns a value of false.

Exercise 14.5 Creating the Retire Method

Next you'll set up a method that enables you to retire a book. This doesn't delete the Book object; it just makes the book unavailable for checkout.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Beginning on the new line, add the following code:

     // Retire the book  function Book_retire(){     If (this.available){         this.retired = true;          trace("You have retired " + this.title);          return(true);      }else{         trace("You can't retire " + this.title + ". It is          currently checked out.");          return (false);      }  } 
  3. Save your file.

Now you can retire a book so that it can't be checked out again.

It seems like the only piece of code you're missing is a method to delete a Book object. Naturally, Flash deletes an object from memory after it is no longer in use, but sometimes you want to explicitly remove an object. There is an operator built into ActionScript that can take care of this for you. You can't just build it into your prototype object. Why? An object isn't allowed to delete itself. To delete an object, you use the delete operator (don't add this to your file right now):

 delete(myBook); 

The delete operator completely removes an instance of the Book object. It's the same as throwing the book into the incinerator.

Exercise 14.6 Attaching the Methods to the Book Object

The last thing you need to do is to attach to your object the three methods you created. The natural approach is to put these lines of code into the object's constructor to manually attach each method to the object.

Although that might be an "obvious" answer, it's not the best one. Instead of trying to attach the methods when a new object is created, you are going to attach the methods to the object using the special prototype object within your object.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Beginning on the new line, add the following code:

     Book.prototype.checkOut = Book_checkOut;  Book.prototype.checkIn = Book_checkIn;  Book.prototype.retire = Book_retire; 
  3. Check your syntax and save your file.

Now you have a full custom prototype object. Your complete code should look like the code in Listing 14.2.

Listing 14.2 The Completed Code for the Book Object
 // Book Object  //                                      // Initialize the Book Object  function Book(author, title, available) {     this.author = author;      this.title = title;      this.available = available;      this.retired = false;  }  // Check the book out  function Book_checkOut(){     if (this.available == true && !this.retired) {         trace("You checked out: " + this.title);          this.available = false;          return(true);      }else{         trace("I'm sorry, you can't check out " + this.title + ". It's          already checked out.");          return(false);      }  }  // Check the book in  function Book_checkIn(){     if (this.available == false) {         trace("Thank you for returning " + this.title);          this.available = true;          return(true);      }else{         trace("You can't check " + this.title + "in. It hasn't been          checked out yet.");          return(false);      }  }  // Retire the book  function Book_retire() {     if (this.available){         this.retired = true;          trace("You have retired " + this.title);          return (true);      }else{         trace("You can't retire " + this.title + ". It is currently          checked out.");          return (false);      }  }  Book.prototype.checkOut = Book_checkOut;  Book.prototype.checkIn = Book_checkIn;  Book.prototype.retire = Book_retire; 

Now you can start to use the methods you just built into your Book object to create some books and then manipulate them.

Exercise 14.7 Creating New Instances of the Book Object

Creating your new objects is a straightforward process. You just use the Book constructor and pass it the parameters it needs to initialize the individual book properties.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Create three new Book objectsmyBook, yourBook, and hisBookby entering the following code:

     myBook = new Book("Clancy, Tom", "The Hunt for Red October", true);  yourBook = new Book("Jordan, Robert", "Lord of Chaos", true);  hisBook = new Book("Stephenson, Neil", "The Diamond Age", true); 

    This gives you three instances of the Book object in your current movie.

  3. You probably want to prove to yourself that those objects are actually there. (See Figure 14.6.) To do so, you need only throw in a few trace actions:

     // Display the contents of the Book objects  trace(myBook.title + " by " + myBook.author + ". Available:  " + myBook.available);  trace(yourBook.title + " by " + yourBook.author + ". Available:  " + yourBook.available);  trace(hisBook.title + " by " + hisBook.author + ". Available:  " + hisBook.available); 
  4. Check your syntax. Save and test your file.

If all went well, you should see all the properties for the three Book objects displayed in the Output window. If not, go back and check your code. Remember: Spelling and capitalization count!

Figure 14.6. After you have created your new objects, you can set up a trace action to display their contents in the Output window.

graphics/14fig06.gif

Exercise 14.8 Using the Methods to Manipulate the Book Objects

Now that you can see the properties of your Book objects, it's time to manipulate them.

  1. Position your cursor after the last curly brace in the Actions list and press Return or Enter to add a new line.

  2. Now it's playtime. Try adding the following lines:

     myBook.checkOut();  myBook.retire();  myBook.checkIn();  myBook.retire();  yourBook.checkIn();  yourBook.checkOut();  hisBook.retire(); 
  3. Save and test your file.

You can monitor what is happening to your Book objects in the Output window. If your Output window doesn't match Figure 14.7, go back and check your code for errors.

Figure 14.7. Now that your objects have been created, you can use their methods to manipulate them. The values of the trace actions displayed in the Output window let you know what's going on. If your output doesn't match this, you need to do some debugging.

graphics/14fig07.gif

First, you check out myBook ( The Hunt for Red October ). Then you try to retire it, but you can't because it's currently checked out. Thus, you check myBook ( The Hunt for Red October ) back in and then retire it. Next you try to check in yourBook ( Lord of Chaos ). But yourBook ( Lord of Chaos ) hasn't been checked out yet, so you can't check it in. Instead, you check out yourBook ( Lord of Chaos ) and then retire hisBook ( The Diamond Age ). Play around with this until you are satisfied that you understand how these methods are working.

So, how did you create your new Book objects? You called the constructor just like you would for any other object. You don't always call the constructor function this way. For example, if you are trying to create an object and that object's prototype hasn't been declared in the same timeline (movie clip) that you are currently in, you have to explicitly reference the timeline where the prototype was declared. If you are working in a movie clip inside the main timeline and you want to create a new Book object inside the movie clip, you have to reference the constructor on the main timeline:

 MyBook = new _root.Book("Seuss, Dr.", "Hop on Pop", 1); 

Note that objects are good candidates for external libraries in Flash because they are fully self-contained. This lets you easily use the same library file for multiple projects. You could place your entire Book object (minus the code from Exercises 14.7 and 14.8) into a text file called Book.as. After you do this, all you have to do to be able to use the code you just wrote is load it into your current file using an include statement. The only line in your Actions list would be this:

 #include "Book.as" 

You then can add in any additional statements you want to use to work with the Book object.



Inside Flash
Inside Flash MX (2nd Edition) (Inside (New Riders))
ISBN: 0735712549
EAN: 2147483647
Year: 2005
Pages: 257
Authors: Jody Keating

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net