Archive for the ‘actionscript’ Category

HOW TO: Delete an XML node using E4X

Monday, April 21st, 2008 |

While creating a sample application for some class content the other day, I ran into an XML/E4X situation that I'd never encountered before. It is pretty basic - deleting a node from XML. How does one do it? With the delete keyword of course!

For example:

Actionscript:
  1. var  myXML:XML =
  2.     <order>
  3.         <item id="0" name="main">Hamburger</item>
  4.         <item id="1" name="side">Fries</item>
  5.         <item id="2" name="drink">Med. Soda</item>
  6.         <item id="3" name="drink">Lg. Soda</item>
  7.     </order>;
  8.  
  9. // Delete the Med. Soda node
  10.  
  11. // Output the XML
  12. trace( myXML.toXMLString() );
  13.  
  14. // Result
  15. //<order>
  16. //  <item id="0" name="main">Hamburger</item>
  17. //  <item id="1" name="side">Fries</item>
  18. //  <item id="2" name="drink">Med. Soda</item>
  19. //  <item id="3" name="drink">Lg. Soda</item>
  20. //</order>
  21.  
  22. delete myXML.item[2];
  23.  
  24. // Output the edited XML
  25. trace( myXML.toXMLString() );
  26.  
  27. // Result
  28. //<order>
  29. //  <item id="0" name="main">Hamburger</item>
  30. //  <item id="1" name="side">Fries</item>
  31. //  <item id="3" name="drink">Lg. Soda</item>
  32. //</order>

Man, E4X is so simple!

http://john.realeyes.com/wp-content/plugins/downloads-manager/img/icons/winzip.gif download: Delete Node Example (4.78KB)
added: 04/09/2009
clicks: 72
description: Code source (.FLA) for delete XML node using E4X in ActionScript 3 sample

Flex and Using Meta Data

Saturday, January 5th, 2008 |

"Metadata is data about data" in the case of Flex it is going to describe our components, classes and their interactions/uses. For example the most familiar metadata tag in Flex and AS3 code is [Bindable] this describes a property that can be bound to (obviously). But metadata is not limited to properties in Flex, you can describe all sorts of things with metadata to make your application code much easier to decipher, easier to user as well and add functionality that might otherwise be missed. I'll try to describe a few of these so you can be on your way to using Flex metadata to improve how you write and use Flex code.

When creating metadata keep in mind that the metadata is bound to the next line in code. So if you are creating metadata for a class property or method, it should immediately precede the property declaration or method definition.

The [Bindable] metadata tag is great for class properties created in declarations but what about Getters and Setters - This is probably the next most used metadata tag that in my code and is an addition of the [Bindable] tag. In order to bind to a property that has a getter/setter you need to declare the event type that is dispatched when the property changes. We add the event="changePropertyName" to the [Bindable] tag:
[Bindable(event="changePropertyName")]

changePropertyName can be any string, but by convention "change" and then the name of the property (in hungarian notation).

Speaking of events, when a class broadcasts and event. You can add metadata for code hinting. To specify the event and its type for a class you can add the [Event] metadata tag. You'll need to specify a name and a type for this tag so FlexBuilder knows what event and type it will present in the code hinting. So the [Event] metadata tag will look like:
[Event(name='changePropertyName' type='flash.events.Event')]

One note about the name value - you'll need to use hungarian notation again so the code hinting displays correctly. So the event above changePropertyName may have a static const on the class CHANGE_PROPERTY_NAME if you follow the changePropertyName (lowercase for the first character and then uppercase for additional words) the code hinting in FlexBuilder will wake up just fine.

For Example - the following event metadata [Event(name="CHANGPROPERTYNAME", type="flash.events.Event")] results in the following code hinting:

Not very code-hinting'ish :)

Where as this [Event(name="changePropertyName", type="flash.events.Event")] results in:

Much better!

When building compoenents in AS3 you'll want to expose information about your component, default values, property names etc. In comes the [Inspectable] metadata tag. This tag is not required and there are a few rules that apply with how Flex Builder displays the information. You can check out the details in the live docs. There are many definitions that you can add to the [Inspectable] tag, but some of the more used declaration in my code are:

  • defaultValue - The initial value that is determined by the property declaration.
  • enumeration - A comma-delimited list of values that are accepted for that property's value.
  • type - Specifies the type of the value. Useful if you need a specific type instead of a generic type
  • variable - Specifies the variable to which the parameter is bound

These are just a few of the metadata tags. There is quite a lot you can do with metadata and it has solved some problems for me. If you'd like to learn more check out the live docs!

E4X XML Namespaces

Tuesday, November 6th, 2007 |

For XML that looks like the following response from Yahoo's weather service:

XML:
  1. &lt;?xml version='1.0' encoding='UTF-8'?&gt;
  2. http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*
  3. http://weather.yahoo.com/forecast/94089_f.html         Yahoo! Weather for Sunnyvale, CA
  4. en-us
  5. Tue, 06 Nov 2007 6:56 pm PST
  6. 60
  7.  
  8.  
  9.  
  10.  
  11.  
  12. <img alt="" />
  13.  
  14. 142
  15. 18
  16.  
  17. http://weather.yahoo.com/             http://l.yimg.com/us.yimg.com/i/us/nws/th/main_142b.gif
  18. 37.39
  19. -122.03
  20.  
  21. http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/94089_f.html Tue, 06 Nov 2007 6:56 pm PST
  22.  
  23. &lt;![CDATA[
  24. <img src="http://l.yimg.com/us.yimg.com/i/us/we/52/33.gif" alt="" />
  25. <strong>Current Conditions:</strong>
  26. Fair, 55 F
  27.  
  28. <strong>Forecast:</strong>
  29. Tue - Mostly Clear. High: 67 Low: 49
  30. Wed - Partly Cloudy. High: 71 Low: 49
  31.  
  32. <a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/* http://weather.yahoo.com/forecast/94089_f.html">Full Forecast at Yahoo! Weather</a>
  33. (provided by The Weather Channel)
  34. ]]&gt;
  35.  
  36.  
  37.  
  38. 94089_2007_11_06_18_56_PST

When you need to access the nodes with complex node names such as yweather:location think XML namespaces.
In the above example, look for the xmlns declaration in the rss node
- xmlns:yweather='http://xml.weather.yahoo.com/ns/rss/1.0'.
Creating a Namespace object using the declaration will allow us to access the nodes with complex names.
Creating a Namespace object is a pretty simple process:

Actionscript:
  1. var yweatherNS:Namespace = new Namespace( http://xml.weather.yahoo.com/ns/rss/1.0 );

Now we can access the node with the following code:

Actionscript:
  1. yahooWeaterXML.channel.yweatherNS::location
  2.  
  3. trace( yahooWeaterXML.channel.yweatherNS::location.@city ); // outputs 'Sunnyvale'
  4. trace( yahooWeaterXML.channel.yweatherNS::location.@region); // outputs 'CA'
  5. trace( yahooWeaterXML.channel.yweatherNS::location.@country ); // outputs 'US'

With the preceding example we need to know the namespace url ahead of time. E4X gives us the namespaceDeclarations() method that will return an array that contains the namespace declarations associated with the XML document

Using the namespaceDeclarations() method from the XML object:

Actionscript:
  1. var namespaces:Array = myXML.namespaceDeclarations();

Now we have an array of namespace declarations that we can use to dynamically declare Namespace objects and access our complex node names:

Actionscript:
  1. var yweatherNS:Namespace
  2. var geoNS:Namespace
  3. var nsLen:uint = nameSpaces.length;
  4. for(var i:uint = 0; i &lt;nsLen; i++)
  5. {
  6. var newNamespace:Namespace = new Namespace( nameSpaces[i] );
  7. if( String( nameSpaces[i].prefix ).toLowerCase() == "yweather" )
  8. {
  9. yweatherNS = newNamespace;
  10. }
  11. else
  12. {
  13. geoNS = newNamespace;
  14. }
  15. }

So we can access the geo and yweather nodes without any problems now.

ApolloRanch in Boulder CO

Saturday, May 5th, 2007 |

ApolloRanch is a mini-conference similar to ApolloCamp. Thanks to Xylem CCI (Xlyem and Creation Chamber merged on April 30th) for putting together and hosting the ApolloRanch, they've done a great job so far! ApolloRanch is at the Fisk Planetarium (shoot for the starts Apollo!) on the CU campus in Bolder.

Mike Chambers gave the keynote as well as a "creating your first Apollo application" presentation.

Here is a frew of the highlights:

  • Apollo Beta to be released on Labs around mid June (keep an eye on Labs)
  • Many of the missing APIs will be in the beta; drag-and-drop, clipboard
  • Philo (Adobe Media Player) Preview: Very interesting media player. RSS feed based "channels" for video contnet delivery (FLV).

Some more of the release timeline:

  • Apollo 1.0, Moxie (Flex 3.0), Philo 1.0 - late Fall early Winter
  • Apollo dot releases - first quarter 2008

Links for the sample apps

Cairngen 1.0 - Now with ANT

Saturday, May 5th, 2007 |

Eric Feminella created Cairngen as a code generation tool for Adobe Cairngorm. he developed it to do away with the redundant copy/paste work needed to create Flex applicatoins with Cairngorm and is released under the MIT license.

Cairngen 1.0 is built entirely in Ant and provides a solution for one-shot code generation of Adobe Cairngorm 2.2 classes.

I haven't had a chance to play with Caringen 1.0, but can't wait (I love ANT!).

Thanks Eric!

Dispatching a custom event

Saturday, March 31st, 2007 |

There are many common events for Flex components, such as the click or change events. These events are very usefull and great for many situations. Your application or custom component may require more from an event than is provided in these built-in events. Not a problem! You can dispatch any of the predefined events inherited by a component's superclass, as well as new, custom, events that you define within the component.

To dispatch a new event from your custom component, you must do the following:

  1. Create a subclass from the flash.events.Event class (or another event class) to create an event class that describes the event object. This step is optional.
    Actionscript:
    1. public class MyCustomEvent extends Event
    2. {
    3. static public var customEventName:String = "customEventName";        public var myEventData:*;
    4.  
    5. public function MyCustomEvent(type:String, p_eventData:*, bubbles:Boolean=false, cancelable:Boolean=false)
    6. {
    7. super(type, bubbles, cancelable);
    8.  
    9. myEventData = p_eventData;
    10. }
    11.  
    12. }

  2. Use the [Event] metadata tag to make the event public so that the MXML compiler recognizes it. This step is optional.
    Actionscript:
    1. [Event(name="customEventName", type="com.events.MyCustomEvent")]
    2. public class MyCustomEvent extends Event
    3. {    ...

  3. Dispatch the event using the dispatchEvent() method.
    Actionscript:
    1. dispatchEvent(new MyCustomEvent(MyCustomEvent.customEventName, eventData));

[Simple Custom Event Sample]

[Simple Custom Event Source]

Flex Doumentation:

Another Labs Release - LiveCycle Data Services 2.5

Tuesday, March 20th, 2007 |

In addition to Apollo, Adobe is releasing an early version of LiveCycle Data Services to the
community to solicit feedback and to continuously improve the product.
This beta release of LiveCycle Data Services includes a number of new
capabilities targeted at enterprise Flex application development.

Check out the release notes for a complete detail of what is in the new version

Here are the deatils.

Cursor postion in a flex TextArea control using the TextLineMetrics class

Tuesday, March 20th, 2007 |

Problem: We want to add a pop-up box to a TextArea control as a user is types a specific word or set of words into a TextArea control. The pop-up box should needs to be at the position of the cursor, but we don't know the x & y position of the cursor.

Solution: With a little coercion and the TextLineMetrics class, we can approximate the x & y position of the cursor.

Example using a TextArea control with the id of myTextArea:

Actionscript:
  1. var textHeight:Number = myTextArea.textHeight;
  2. var lineHeight:Number = myTextArea.getLineMetrics( 0 ).height;
  3. var numLines:Number = Math.ceil( textHeight/lineHeight );
  4. var currentLineMet:TextLineMetrics = myTextArea.getLineMetrics( numLines-1 );
  5. var xPos:Number = currentLineMet.width + myTextArea.x;
  6. var yPos:Number = textHeight + predict_ti.y - ( lineHeight * myTextArea.verticalScrollPosition );

The TextLineMetrics class contains information about the text position and measurements of a line of text within a text field. All of the measurements are in pixels, so we are just aproximating the x & y position.

[View Sample]
[Download Source]

The problem with the above example is that it only works for the last character that you type into the TextArea. If we want to get the actual cursor position we'll need to create a custom component using the a TextField.

Below is a link to a simple component that figures out an approximate x & y based on the index of the character 1 less than the current position of the carat within the TextField.

[View Sample]
[Download Source]

Flex: Simple Predictive Text Example

Monday, March 19th, 2007 |

We built a predictive TextInput component in an AS2 for a project that we have been working on for a client. I thought it might be good practice to port it to Flex. I've created a very simple example of a predictive text component that uses a local ArrayCollection to populate the results. Obviously the functionality is quite limited, the concept is there. Next on the list of things to do would be to capture keypresses for up and down arrows so the user could select an item in the list more easily as well as creating a more robust data provider example (possibly from Google or something). I'll be sure post any updates.

[Check out the sample]

[Download the source]

The Rest of ApolloCamp

Sunday, March 18th, 2007 |

Well, I tried to get up a post about the rest of the ApolloCamp presos the next morning, but my connection was crap, and the post seems to have been lost, so here goes the rest.

Kevin Hoyt – Nice Presentation on the File API. One huge bonus is the ability to read and write ActionScript object directly. I've played with the file IO stuff a little so this was cool to see.

Daniel Dura – Awesome "cookbook" session lots of good. Quick examples, of the Apollo's windowing etc.

EUI – Gave a presentation on a desktop application they have been working with Ebay on. The cool thing here wasn't really the application, although some of the features of the app (data filtering) were right up there, but the Java Bridge framework that EUI has been working on. Codenamed Artemis, it allows for access to low-level system functions through Java. Think a wii-mote controlled light saber on the big screen. You can learn more at http://artemis.effectiveui.com/.

Finetune – Showed off their media player that they have been working on. Very cool features like recognizing a playlist on someone's site and keeping it playing in the desktop application when you leave that persons site!

I'm sure I've forgotten quite a bit of all the cool stuff that was presented. I do want to give a big thanks to all those involved with ApolloCamp. It was a great event, and I'm sure a ton of work. Good job everyone!

Find entries :

Want to subscribe?

  Subscribe in a reader or,
Subscribe via email:

About me

I'm a senior developer at RealEyes Media, Adobe Certified Instructor and Adobe Certified Professional. Here you'll get my ideas and experience Flex, Flash, ColdFusion and related technologies as well as some generally off the wall stuff.