Specifying a file as the source of a model might lead you to think that the file would be read in at runtime but you’d be wrong. The XML is actually compiled into the SWF.
Loading a file at runtime requires you to use the HTTPService class. To do this you need to:
- create an HTTPService object
- invoke it’s send method (often as part of the application creationComplete)
- handle the data returned
You create the object by (at a minimum) specifying an id and a url for the location of the data (either a web address or file system location). An example would be:
<mx:HTTPService id="myService" url="http://www.myserver.com/myFile.xml />
Flex is subject to the security constraints of FlashPlayer which means that and application loaded on domain 1 cannot load data from domain 2 unless domain 1 is specified in a crossdomain.xml file on domain 2. A file that would allow anyone access would look like:
The returned data can be handled in two different ways – either via data binding or using a result event handler.
When you use data binding, the result is stored in a variable named lastResult. To access part of the xml data you would use the following format –
To handle the data via an event, specify the event handler function for the result property in your HTTPService definition. You can also define an event handler for the fault property in case there’s a problem retrieving the data.
The result handler will require an event parameter of type ResultEvent and the data can be accessed using the format –
By default, complex data structures are returned as ArrayCollections. When an ArrayCollection used in a data binding changes, the visual component it is bound to is automatically updated. It is important to note that this is not the case if you use a regular array object. The ArrayCollection class needs to be imported to be used in your application.
List based controls (such as list, tree, dataGrid etc) use a dataProvider property to bind to data which can be set to an ArrayCollection. When using a list, it’s important to specify the labelField property to tell the list what property of the ArrayCollection is to appear.
Items can be added to an ArrayCollection using either the addItemAt method and specifying the item and the position (zero based index) or addItem which will add the item to the end of the collection.