Newsletter: Learn More ||| Multimedia Presentation Software |||
Nuts & Bolts.Variables (MX)
Contents
Introduction
Basic data types in Flash MX and Flash 5 include numeric, string and boolean, and structured types include array and object. Variables may be created for any of those data types. As in any programming language, variables are created to hold data which may change throughout the program (movie), or which is to be applied in a loop, for example (to avoid a lot of duplicative code).
New in Flash MX
Variables in Flash MX are essentially the same as in Flash 5. One exception is that in Flash 5, you could treat a dynamic textfield as a string variable; in Flash MX it is better (more powerful) to treat a dynamic textfield as an instance of the Textfield class, giving it an instance name instead of a variable name, and accessing its content via its .text property.

Naming conventions have also changed (or been added, actually) with Flash MX; the preferred naming convention is to end a variable name with a suffix that indicates what type of object it is (_str for string, _txt for textfield, _pb for FUI pushbutton, etc). This allows the default codehints file that comes with Flash MX to be used to provide context-relevant information while you type. Of course, you can use the same naming convention in a Flash 5 file; it just won't bring up special codehints.

In Flash MX, you can also specify a variable as global, so it can be accessed from any timeline, and from movies loaded into any level, without specifying a path. To declare such a variable, use this form:

_global.dbname_str = 'Addresses';

The variable can then be accessed from anywhere as simply dbname_str (instead of this._parent._parent.dbname_str, eg). Some recommend the use of namespaces with _global to avoid potential naming conflicts, especially in files which will be shared. The format would then be

_global.astb.dbname_str = 'Addresses';

making the variable accessible as astb.dbname_str. Functions, which are actually a kind of variable, can also be defined as global and accessed in the same way from anywhere in the movie. This is a good technique to use for class constructor functions, so that new instances can be created anywhere in the movie.
Variable Naming Conventions
Flash MX and Dreamweaver MX both supply the developer with a handy feature called code hints, wherein all of the properties and methods for an object type are displayed (in a list which may be selected from) when the name of a variable of that object type is typed (in a .fla in Flash MX, or an .as file in DWMX), provided the developer follows certain naming conventions for variables. These conventions are stored in definitions in the ASCodeHints.xml file found in the Flash MX/First Run/ActionsPanel directory under the Macromedia directory in Program Files (on a PC), and for FUI component variables in UIComponents.xml in the CustomActions subdirectory. You only need to know that if you want to change the definitions, though. Otherwise, you can just use the conventions supplied for your variable names and the appropriate code hints will pop up. The default conventions are these:

In ASCodeHints.xml:
<typeinfo pattern="*_mc" object="MovieClip" />
<typeinfo pattern="*_array" object="Array" />
<typeinfo pattern="*_str" object="String" />
<typeinfo pattern="*_btn" object="Button" />
<typeinfo pattern="*_txt" object="TextField" />
<typeinfo pattern="*_fmt" object="TextFormat" />
<typeinfo pattern="*_date" object="Date" />
<typeinfo pattern="*_sound" object="Sound" />
<typeinfo pattern="*_xml" object="XML" />
<typeinfo pattern="*_xmlsocket" object="XMLSocket" />
<typeinfo pattern="*_color" object="Color" />
<typeinfo pattern="_level*" object="MovieClip" />
<typeinfo pattern="_parent" object="MovieClip" />
<typeinfo pattern="_root" object="MovieClip" />
in UIComponents.xml:
<typeinfo pattern="*_ch" object="FCheckBox"/>
<typeinfo pattern="*_pb" object="FPushButton"/>
<typeinfo pattern="*_rb" object="FRadioButton"/>
<typeinfo pattern="*_lb" object="FListBox"/>
<typeinfo pattern="*_sb" object="FScrollBar"/>
<typeinfo pattern="*_cb" object="FComboBox"/>
<typeinfo pattern="*_sp" object="FScrollPane"/>
<typeinfo pattern="globalStyleFormat" object="FStyleFormat"/>

That is, if you name a string variable address_str or lastname_str or anything_str, code hints for string objects will pop up as soon as _str has been typed in. You can also make a copy of this file, save it, and enter your own preferred patterns into the file -- either modifications of existing ones or new ones. I use these changes and additions:

< typeinfo pattern="*_arr" object="Array" />
< typeinfo pattern="*_bmc" object="MovieClip" />
< typeinfo pattern="*_itxt" object="TextField" />
< typeinfo pattern="*_htxt" object="TextField" />

because _arr is shorter than _array and because I like to be able to identify in my code which textfields are input fields or html-formatted fields, as opposed to ordinary dynamic textfields, and which movieclips are expected to function as button movieclips.
Assigning a value to a simple variable
Variables of type string, boolean or number may be created and assigned a value by just typing the variable name, followed by an "=", followed by the value:

var name_str = "Wanda Jones"; // string
var i = 0;   // numeric, i is often used for looping
var isFinished_bool = true;   // boolean (no quotes around true)
var hasCake_bool = 0;   // also boolean, same as hasCake_bool = false;


To get the contents of an input textfield into a variable, one should assign the .text property of the textfield to the variable if the variable is a string variable, or the converted numeric value of .text if it is a numeric variable:

var phone_str = phone_itxt.text; // string
var houseNumber_n = Number(houseNumber_itxt.text);   // numeric
var sum_n = Number(a_itxt.text) + Number(b_itxt.text);   // numeric


Converting textfield contents to a numeric value with the Number function is especially important when one wants to perform numeric addition using the textfield contents -- if no conversion is done, Flash will interpret the "+" as the concatenation of two strings instead of addition of two numbers.
What is var
Each of the statements above begins with the keyword "var". This declares the variable as local within whatever function it resides, if it resides in a function. That is, nothing outside the function can see, or access the value of, that variable. Declaring local variables is a good habit because it enables Flash to more efficiently find the variable -- it searches within the function only and doesn't have to look elsewhere to find it. It also helps prevent accidental changes to variables with the same name outside the function. Var declarations may be made on several variables at once at the start of the function, such as

var i, name_str, names_arr;

or they can be declared in code the first time they are assigned a value, as above. Here's an example which shows that variables declared with var (in this case, variable things_arr) are not directly accessible outside the function:

function getFirst() {
   var things_arr = ['house','frog','branch'];
  return things_arr[0];
}  
trace(getFirst()); // house
trace(things_arr[0]); // undefined


but if you remove var from the statement in getFirst, the second trace will also return "house".
Structured data types
Flash provides two useful variable structures, array and object. You can create an empty array or object and add elements/properties later, or create the array or object and assign values all in one statement:

Creating an array
Any of these will work to create an array (an object of type Array):

  var names_arr = new Array(5);
  var names_arr = [];
  var names_arr = ['Frank', 'Lisa', 'Steve'];


The first statement says create a new array with 5 elements, but don't assign any values to those elements. The second statement creates a new blank array of length 0. The third statement creates an array with 3 elements that have values. Useful properties/methods of arrays include .length, .push, .pop, and .splice. More on arrays may be found at the array object page(s).

Creating an object
Any of the following will work to create a object variable (an object of type Object):

  var people_obj = new Object();
  var people_obj = {};
  var people_obj = {name:'Jane', dob:'2/3/1988', imname:'dancer7938'};


The first two statements above are identical; they create a new object people_obj with no properties. Properties may be added later by simply assigning them, as in people_obj.name="Jack". Alternately, properties may be assigned when the object is created, as in the third statement above. Properties of objects may be accessed via either dot syntax, as in people_obj.name, or via associative array syntax, as in people_obj["name"].

Creating an object of a predefined class
Flash MX (and Flash 5) comes with a number of predefined classes, that is, classes which may be used to assign certain predefined properties and methods to an object of that class. Date, Color, Array, and Sound are examples of such classes. To create an instance of a class, use the "new" operator, as was done above for array and object creation. Eg, to create variable wedding_date, an instance of the Date class:

var wedding_date = new Date(1985,9,15);

Creating a custom object
In addition to creating new instances of builtin objects with the "new" operator, you can also define your own class, with whatever properties and methods it needs, and create new instances of it. Here is kind of a silly example (but it illustrates the concept and method) which creates a Titles class and two instances of it. Each instance calls the makeGreeting method of Titles to create a greeting string:

// constructor function for Titles class
// m = male title, f = female title, isBefore = boolean value indicating
// whether the title should appear before or after the person's name
function Titles(m, f, isBefore) {
  this.m = m;
this.f = f;
this.isBefore = isBefore;
}
// makeGreeting method of Titles class
// returns a string with the title and name appended in correct order
Titles.prototype.makeGreeting = function(name_str, gender_str) {
  if (this.isBefore) {
return (gender_str.toLowerCase()=='f' ? this.f : this.m) + ' ' + name_str;
} else
{
return name_str + ' ' + (gender_str.toLowerCase()=='f' ? this.f : this.m);
}
}  
// create instances of the class
var engFamTitles = new Titles("Uncle", "Aunt", true);
var chiFamTitles = new Titles("shushu", "ayi", false);
// using a method of the class to do something to the two instances
trace(chiFamTitles.makeGreeting("Zhao", "f")); // Zhao ayi
trace(engFamTitles.makeGreeting("Joe", "M")); // Uncle Joe


Creating an array of objects
A final example that uses a combination two structures: one of the most useful structures for dealing with recordsets returned from a database is with an array of objects, where each element of the array represents one record, and each property of the object is one field in the record. Here's an example of such a structure being used to hold n records returned via a LoadVars object where fields are returned with a recordindex -- 0, 1, 2, etc -- appended to each fieldname:

this.data_lv.onLoad = function() {

// for each record returned:
for (var r=0; r < this.n; r++) {
// create a new element of array content_arr
// (content_arr is a property of the recordset object (this.owner))
// each element of content_arr is an object representing one record
this.owner.content_arr.push(new Object());
  // for all fields in the record:
// (fields_arr holds definitions of each field in the table)
for (var f=0; f < this.owner.fields_arr.length; f++) {
 
var field_str = this.owner.fields_arr[f].name;
// get name of returned variable (=field name + index)
// assign to same named property of content_arr[r]
this.owner.content_arr[r][field_str] = this[field_str + r];
  }
}  

}

This tutorial was written by Helen Triolo.
 
©2007 Wildform, Inc | Policies | Contact Us | Newsletter Options
 
©2010 Wildform, Inc | Policies | Contact Us | Newsletter Options
 
Wildform provides a 100% satisfaction guarantee on all our Flash software. If you are not completely satisfied with our Flash multimedia software for any reason you may request a refund within 15 days of purchase.