Monday, November 2, 2009

Flex Code Behind

ASP pages usually are made of a frontend and a backend. I am by no means a Microsoft fan, but I do like the separation of markup and logic. Coming from a flash background having a separate ActionScript file with all my code just feels right.

With Flex there is no need for AS files. All the code could be in the MXML and use script tags, but I think script tags complicate the view. Instead of using script tags. Make an ActionScript class that extends the UIComponent you want to inherit and make an MXML class that inherits from your ActionScript class. I like to name the MXML class something descriptive and use the same name plus Class for the ActionScript class.

Example:
ProductView.mxml
ProductViewClass.as

To share functions: Define a protected or public function in the AS class and call them in the MXML.
To display information in the MXML make protected variables and data bind to them, preferably a model object. I will omit a MVC discussion for later.
To alter MXML elements, I prefer to data bind to variables, but if you need a handel to a UIComponent give it an ID in the MXML and create a public variable in the AS class. Try to avoid this. It makes your ActionScript class depend on the MXML. Instead most updates can be done by data binding to variables that change in the AS class.

Here is a simple example of a ProductView with a code behind class. The MXML data binds to a product, and the code behind reads the qty.text. I will include more examples in future posts.

ProductView.mxml

<?xml version="1.0" encoding="utf-8"?>

<ProductViewClass

 xmlns:mx="http://www.adobe.com/2006/mxml"

 xmlns="view.*"

 >

 <mx:HBox >

  <mx:VBox>

   <mx:Label text="{product.description}" />

   <mx:Label text="Price ${product.price}" />

  </mx:VBox>

  <mx:Label text="Qty: " />

  <mx:TextInput id="qty" enter="addToCart()" width="33" />

  <mx:Button label="Add To Cart" click="addToCart()" />

 </mx:HBox>

</ProductViewClass>


ProductViewClass.as

package view

{

 import model.Product;

 import mx.containers.Canvas;

 import mx.controls.Alert;

 import mx.controls.TextInput;


 public class ProductViewClass extends Canvas

 {

  [Bindable]

  protected var product:Product;

  public var qty:TextInput;

  public function ProductViewClass()

  {

   product = new Product();

  }

  protected function addToCart():void

  {

  Alert.show( "Add to cart qty:"+qty.text ); 

  }

 }

}

No comments:

Post a Comment