| By Guy Watson | Article Rating: |
|
| March 2, 2004 12:00 AM EST | Reads: |
13,701 |
With any new version of a software product, a whole new host of features is introduced - Macromedia Flash MX 2004 is no different. It has been rebuilt for the ground up with a new JavaScript API (Flash JavaScript), which enables developers to extend the functionality of the authoring tool. This two part article explores features of this new architecture. Part 1 gets you started with a general introduction to the Extensibility Layer, the fundamental Document Object Model, and the relationship between different parts of a Flash Document and their associated objects. Part 2 will cover building your own Flash Panels and will include an in-depth look at XML2UI - Flash Dialog Boxes.
The 'Extensibility Layer'
With any new version of a software product, a whole new host of features is introduced - Macromedia Flash MX 2004 is no different. The most significant new feature in the latest release of Flash is the "Extensibility Layer."
The "Extensibility Layer," as Macromedia calls it, is a general term that covers a range of new, exciting features that make it possible for Flash developers to create and implement their own new features directly into the Flash Authoring Environment. Various third parties are already commercially distributing their own Flash Extensions that add new features to the IDE. For example, the makers of SWiSH, the ever-popular text effect tool, are now selling a Flash extension called SWiSHpowerFX that allows Flash designers to select a text field on the stage and apply various SWiSH text effects to that text.
The Extensibility Layer makes it possible to write macros that will automate common tasks, write tools that manipulate objects on the stage, create panels that contain graphical user interfaces, write Timeline effects that animate objects on the stage and much, much more...
Introducing JSFL
Taking advantage of these new possibilities requires knowledge of a new scripting language that lets us talk to the Flash MX 2004 IDE and tell it what to do. This new language is commonly called JSFL.
Those of you who have seen snippets of JSFL floating around may have noticed a striking similarity between that and ActionScript or JavaScript. Well spotted! The good news is that Macromedia based JSFL on the Netscape JavaScript API, which means that ActionScript coders like me, or anybody who has dabbled in JavaScript, won't have to learn a whole new programming language. The syntax is exactly the same, dot syntax, and we still work with the same data types: objects, arrays, strings, numbers, and functions.
As this article is written for Flash developers, it assumes knowledge of ActionScript.
JSFL is based around a Document Object Model (DOM) that exposes a hierarchy of objects that represents the structure of a Flash document in the form of a hierarchical tree, very similar in nature to a family tree. Each object allows you to dynamically access and update the structure of a Flash document. The key to learning to write your own Flash extensions is to understand the Flash DOM, which I cover in great detail in this article.
Types of Flash Documents
Flash MX 2004 works with two types of documents; the first is the standard timeline-based document that users of previous versions of Flash are familiar with, and the second is screen-based documents, which have been introduced into Flash MX 2004. Screen-based documents use a different metaphor for organizing your movies, and you will know them as Form Applications and Slide Presentations.
The DOM of a screen-based document differs slightly from that of a timeline-based document, and because timeline-based documents are the most common document I cover only their DOM in this article.
Anatomy of a Flash Document
To begin with, think about each of the different parts of a Flash document. Flash documents comprise:
- Timelines
- Layers
- Frames
- Symbols
- Shapes
- Text fields
- Library
- MovieClips
- Buttons
- Graphics
- Bitmaps
- Sounds
- Videos
- Components
Note: It's important to realize that Flash works with groups of frames (not individual frames); a group of frames begins with one keyframe and ends at the frame before the next keyframe on that layer, or the last frame in that layer, whichever is first. Each frame in a group of frames refers to the first frame in the group (the originating keyframe).
The Flash DOM represents this hierarchy and each separate element of a Flash document as objects. So there is a unique object for each layer in a Flash document; there is also a unique object for every frame in a Flash document, and so on.
These objects have properties that describe that particular element; for example, all layer objects have a "name" property that contains the name of that particular layer.
Image I contains a timeline that contains one layer; this layer is named "Layer Name". In JSFL, we can access the name of that particular layer using
theLayerObject.name;
Each type of object may also have associated methods that manipulate that particular object in its visual form in the Flash IDE; for example, all timeline objects have a method called "deleteLayer" that removes a particular layer from that particular timeline.
In JSFL, we can get Flash to delete the first layer of a timeline using:
theTimelineObject.deleteLayer(0);
Object Relationships
These objects have a parent/child relationship; each layer object contains references to its child frames, which are grouped together in an array. It is therefore said that a frame object is a child of a layer object. The parent of a layer object is the timeline object, which represents the timeline in which that particular layer resides. These relationships are similar in practice to a nested MovieClip hierarchy in a Flash movie.
When a JSFL script is executed, an object is created for each separate element in every Flash document that is presently open in the Flash IDE. Thus your scripts can refer to any element of any of the open Flash documents using dot syntax to traverse that particular document's DOM.
Image II shows the parent-child relationship between the different elements of a Flash document and the hierarchical tree structure.
Think of each section in Image II as a separate class or type of object. Child objects that are the same color as their parent are simply subclasses of their parent, or extensions of the parent object type. For example, Shape is a subclass or extension of the Element object; similarly, FontItem is a subclass or extension of the Item object.
In Image II labels point to the intersections between various objects. If an intersection represents a subclass or object relationship (the color of the parent and children is the same), then the label will contain the property you need to access to determine the type of object you are working with.
If, however, the parent-child relationship represents an object type, which can be accessed as a child of the parent, then the label will tell you the property you need to access to reference each child element. For example, the relationship between the Library object and the Item object is not a subclass relationship since the colors of parent and child are different. Thus, the label tells us that we can access the child items of the Library object using the library.items property, which is an array in which is a collection of Item objects.
Here's a simple example: let's say I have a Flash document that contains one MovieClip on the stage of the first frame of the first layer of the first scene. To access that MovieClip's object, I would have to traverse the DOM using dot syntax as follows:
theMovieClipObject=flash.documents[0].timelines[0].layers[0].frames[0].elements[0]
In this particular example, we know that the one and only element on the stage is a MovieClip, and at times there will be numerous elements on the stage. As illustrated in Image II, an element can be of type Shape, type Text, or type Symbol; and the properties available to those objects differ, thus we need to determine what type of element we are working with. To do this we use the elementType property:
theElement=flash.documents[0].timelines[0].layers[0].frames[0].elements[0]
elementType=theElement.elementType
The elementType property can have three possible values: "shape", "text", or "symbol." If the element is a MovieClip, graphic, or button, then the value of the elementType property will be "symbol", and thus we now know that we are working with a Symbol object. This means that our Element object will contain all the properties that that Symbol object contains.
Top of the Tree
A parent-child relationship has to stop somewhere; therefore, there is always one root object, the "top of the tree" or the "daddy of daddies," so to speak. In the Flash DOM, the root object is the object that represents the Flash application.
Note: The Flash application has its own object, and each Flash document is a child of that object. This object is always accessible in JSFL scripts and goes by the name "flash". It can also be accessed using the shorter name "fl".
The root object contains the child objects that represent each Flash document presently open in the Flash IDE; these document objects are grouped together in a property called "documents" that is an array:
flash.documents
To access the object of the first document open in the Flash IDE with a JSFL script, I would use:
firstDocumentObject=flash.documents[0];
The "flash" object also has various methods that allow you to manipulate the actual Flash application and mimic the actual functionality the Flash application provides; for example, in the Flash IDE it's possible to close the Flash application by simply opening the File menu and then selecting the Quit option. We can do the same thing with JSFL in our scripts by calling:
flash.quit();
In the Flash IDE, it is also possible to close the currently focused document simply by opening the File menu and selecting the Close option. Again, we can do the same thing with JSFL in our scripts by calling:
flash.closeDocument(theDocumentObject);
For a full list of the various objects and their associated methods and properties, check out Macromedia's official JSAPI Documentation at http://livedocs.macromedia.com/flash/mx2004/jsapi/index.htm.
Predefined Classes
As with ActionScript, JSFL has a set of predefined classes containing methods and properties:
- Array
- Boolean
- Date
- Function
- Math
- Number
- Object
- RegExp
- String
In JSFL, as in ActionScript, every string is an instance of the String class, every array is an instance of the Array class, every number is an instance of the Number class, and so on. This means that strings, numbers, arrays, Booleans, objects, etc., are treated in exactly the same way as they are in ActionScript.
All Strings have the usual String methods: "substr", "charAt", "indexOf", etc. All Arrays have the usual Array methods: "splice", "pop", "push", etc.
For example, we can do:
myStr="A,B,C,D";
bits=myStr.split(","); //use a string method
Or:
myStr="abcd";
myStrLen=myStr.length; //get a string property
In both JSFL and ActionScript the above code snippets produce the same result. For a complete list of classes, available methods, and properties refer to the Netscape JavaScript API Web site (http://devedge.netscape.com/central/javascript/).
Top-Level Properties and Methods
JSFL also contains some top-level functions; these are functions that are not related to any particular object or class and thus can be used anywhere in your scripts.
- encodeURI
- decodeURI
- eval
- Infinity
- isNaN
- Number
- parseFloat
- parseInt
- alert
Writing a JSFL Script
You create a JSFL script like you would an external ActionScript file. Using your favorite script editor, write your JSFL code, then save the file with a .jsfl extension. You can call the file whatever you like as long as it has the correct file extension.
The Flash MX 2004 Authoring Tool has a built-in JSFL Script Editor, which is the same as the ActionScript Editor. You can use it to create a new JSFL script by opening the File menu and then selecting New > Flash Javascript File.
You can also open JSFL scripts for editing in Flash MX 2004. Naturally, your JSFL script will automatically open for editing in the JSFL Script Editor. To edit a JSFL script in Flash MX 2004, open the File menu and then select Open. From there you want to navigate through your local machine to find the correct JSFL script to edit.
As with the ActionScript Editor, the JSFL Script Editor also contains a list of every available object and its available methods and properties along the left-hand side. This comes in very handy as there are a lot of them to remember. Roll over a particular method or property on the left-hand side and you will get a tool tip that briefly describes what that particular method or property does (see Image III). The JSFL script editor also has syntax highlighting and code hinting.
Executing a JSFL Script
To execute a JSFL script, the Flash MX 2004 IDE must be open. The simplest form of a Flash extension, the command has its own special place in the Flash MX 2004 IDE - the Commands menu. In the Commands menu is a Run Command option. When you choose this option, you can then locate a JSFL script to execute. The Commands menu displays three default options, but it also adds a new option for each JSFL script contained within a special Commands directory in the Flash MX 2004 Configuration folder. The location of the special Commands directory on your local machine differs with different operating systems.
If you place your JSFL scripts in this directory, you can execute them directly from the Commands menu by selecting the appropriate Commands name from the list of options. The name that is displayed in the Commands menu is simply the name of your JSFL Script file (see Image IV).
As shown in Image IV, I have four JSFL Scripts, located in my Configuration /Commands directory, with the file names:
- Batch Run.jsfl
- Convertor.jsfl
- Save Copy As.jsfl
- Test.jsfl
When a JSFL script is executed, all functions that are called update the state of a particular element in a Flash document immediately, which differs from ActionScript execution.
For example, in ActionScript, if we were to move a MovieClip across the stage in a for loop, we would see only the final state of the loop as the stage is not updated until the ActionScript has been executed. However, if we were to call the "deleteLayer" function of a Timeline object in JSFL inside a for loop, the layer is immediately deleted and the Authoring Environment will refresh to display the new state of the timeline, before the code after the for loop is executed.
The History Panel
The Flash MX 2004 IDE contains a History panel: Window>Other Panel>History. The History panel tracks every interaction you make with the Flash MX 2004 IDE. Each interaction is listed in the History panel as a separate action in the order in which the actions took place. At any time, you can select one or more of the actions you previously performed and replay them. For example, if you draw a new rectangle on the stage, a new action is listed in the History panel (see Image V).
If you then deleted that rectangle from the stage, you could draw that rectangle in exactly the same place, at exactly the same size, by simply selecting the Rectangle action from the History panel and then clicking the Replay button, or by right-clicking the action and selecting the Replay Steps option from the dropdown list that appears (see Image VI).
When you undo a change you have made in Flash MX 2004, using File>Undo (CTRL + Z), that particular action is then removed from the History panel. The opposite is true when you then choose to redo that action because you didn't mean to undo it in the first place: File>Redo (CTRL + Y). The action is then added to the bottom of the actions list in the History panel.
The History panel makes it really easy to build commands that automate particularly tedious or common tasks. The process of creating a Command file with the History panel is fairly straightforward: clear the History panel so you can start fresh.
Now perform a sequence of actions in the Flash MX 2004 IDE that you want to use regularly. Select the group of actions you performed in the History panel and then click the disk icon in the bottom right-hand corner. Enter a name for your command and then click the OK button.
You now have a new command in your Commands menu that when selected will execute and perform that particular sequence of actions. The .jsfl file has been created for you and saved into the correct directory, such that it is displayed in the Commands menu.
There are technical limitations with the History panel; some of the interactions you make with the Flash MX 2004 IDE cannot be replayed. As you play around, you will notice that certain actions contain a red cross. These are the actions that cannot be replayed.
But it doesn't stop there; the History panel can also display the JSFL actions required to perform a particular interaction within the Flash MX 2004 IDE. This comes in handy when trying to learn how to make Flash do something with the JSAPI. So, for example, if you want to know which function to use to add a new layer to the current timeline using JSFL, you can tell the History panel to expose the function calls, by changing the view settings (see Image VII).
Then you can manually add a new layer to the timeline, which will add a new action to the list in the History panel (see Image VIII).
You can then copy that function call by right-clicking the selected actions and selecting to Copy Steps (see Image IX).
You now have the JSFL code in your clipboard, which you can then paste directly into any text editor.
Flash Panels
As I mentioned in the introduction, it is possible to add new panels to the Flash MX 2004 IDE. You can create your own panel by simply creating a Flash movie and then saving it into the correct directory.
The panel can be opened by selecting it from the Window>Other Panels menu. The name associated with the panel you have created and thus displayed in the Other Panels menu is simply the name of the .swf file you placed in the WindowSWF directory. When you select your panel from the menu, your Flash movie is automatically displayed inside a panel, and the size of the panel is automatically determined by the size of your Flash movie.
I've created a Flash movie and named it Auto Save.swf. I then save that Flash movie into the WindowSWF directory. The next time I restart Flash MX 2004, a new option has appeared in the Other Panels menu.
When I select the new Auto Save option, a new panel opens that contains my Flash movie.
ActionScript and JSFL
Flash movies that run in the Flash MX 2004 IDE can execute a string of JSFL using a special ActionScript function. This means that your Flash Panels and XML2UI dialog boxes that contain Flash movie controls can modify/update the Flash document from a Flash movie. The JSFL code you execute can also return a value back to ActionScript. The ActionScript function is called MMExecute, and it can be used anywhere in your Flash movie.
The syntax is simple:
MMExecute("yourStringOfJSFL");
I can create a new panel, as above, and in the Flash movie for that panel I can execute a string of JSFL that will delete a layer when a button is pressed. This would be achieved with the following ActionScript:
MyButton.addEventListener("click",this)
This.click=function()
{
MMExecute("flash.getDocumentDOM().getTimeline().deleteLayer();")
}
When the button is pressed, the MMExecute function passes the JSFL string passed as an argument to the Flash MX 2004-JSAPI Interpreter, which then runs the JSFL code in exactly the same way that a command is run.
It's also possible to access the value of a JSFL property due to the fact that the MMExecute function will return a value, so if I wanted to check that the computer that is running my Flash panel is currently connected to the Internet, I could use the following ActionScript:
HasInternetConnection=MMExecute("flash.isConnectedToInternet");
In the above code, the ActionScript variable "hasInternetConnection" will contain a Boolean value, which was received from the JSAPI Interpreter.
MMExecute will wait for a return value before it runs the next line of code in your ActionScript. It is recommended that if you want to execute a large JSFL script from ActionScript, you place the JSFL script in a .jsfl file and then use the "flash.runScript" function to execute the JSFL script within that file.
Here is an ActionScript function that will execute the JSFL code within a .jsfl file:
function executeLargeJSFLScript(fileURI)
{
return MMExecute("fl.runScript('"+fileURI+"');")
}
And you can use it like this:
executeLargeJSFLScript("file:///C:/myscript.jsfl");
Notice that the fileURI in the above example doesn't contain back slashes, it contains forward slashes and a file:/// protocol prefix.
The following would be incorrect:
executeLargeJSFLScript("C:\myscript.jsfl");
This is a common mistake. All the functions exposed to us in our JSFL scripts that accept a fileURI as an argument, such as "flash.saveDocumentAs", require the string to contain a file:/// protocol prefix and to contain forward slashes instead of back slashes.
One really useful implementation of MMExecute would be if you wanted a Flash movie running in the Flash MX 2004 IDE to work with regular expressions. As ActionScript doesn't support regular expressions, it's possible to send them the JSAPI Interpreter using MMExecute, and the return value(s) will be returned to ActionScript.
That should be enough to get you started. Part 1 of this article covered a general introduction to the extensibility layer, and discussed the fundamental Document Object Model and the relationship between different parts of a Flash document and their associated objects. It introduced the new Flash JavaScript Editor in Flash MX 2004 along with the History panel, and showed you how to build your own Flash panels. When developing Flash extensions, it is sometimes neessary to provide a dialog box, which prompts the user to make a choice or customize settings of extensions in an intuitive and user-friendly way. In Part 2 we'll take an in-depth look at XML2UI - Flash Dialog Boxes.
Published March 2, 2004 Reads 13,701
Copyright © 2004 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Guy Watson
Guy Watson (aka FlashGuru) has been a well-recognized figure in the Flash community for around four years, supporting the community with tutorials and source files, moderating the large Flash community forums, and running his own Flash resource Web site - FlashGuru's MX 101. Guy was one of the two developers that created the award-winning zoom interface for Relevare and now works for Endemol UK, the creative force behind reality television, producing programs such as Big Brother and The Salon. Guy now spends most of his time developing Flash games and applications for high-profile clients such as Channel 5 Television, Ladbrookes, and UK Style.
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe Unveils LiveCycle Enterprise Suite 2 for Deployment in the Cloud
- Adobe Flex Developer Earns $100K in New York City
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Ph.D. in Twitter Anyone?
- Eolas Sues the Internet
- Adobe LiveCycle Enterprise Suite 2 for Cloud Computing
- Adobe Betas Target RIAs and Cloud Computing
- Special Report on the Emerging Cloud Computing Trend
- Adobe Cans Another 9% of its Workforce
- My Thoughts on Ulitzer
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Ulitzer Live! New Media Conference & Expo
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Cloud Executives Feature on Cloud Computing Expo Power Panel
- Software Flexibility in the Cloud - Part 4 of 5
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Is Microsoft as Free as Open Source?
- Adobe Reader Sued
- Adobe Unveils LiveCycle Enterprise Suite 2 for Deployment in the Cloud
- Where Are RIA Technologies Headed in 2008?
- Cover Story: How to Increase the Frame Rates of Your Flash Movies
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Your First Adobe Flex Application with a ColdFusion Backend
- Adobe Flex 2: Advanced DataGrid
- i-Technology Blog: Death-Knell For "Rich Media? Hardly!
- Adobe/Macromedia - Microsoft, Look Out!
- How To Create a Photo Slide Show ...
- Adobe Flex Interface Customization - Themes, Styles, Skins
- Personal Branding Checklist
- Has the Technology Bounceback Begun?
- "Real-World Flex" by Adobe's Christophe Coenraets



































