Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Thursday, November 6, 2008

Creating an ItemRenderer in ActionScript

I'm posting this for my benefit as much as anyone else. Here is a very basic ItemRenderer done in ActionScript. Something you might come across when building Flex/Air applications is errand problems with ItemRenderer's not performing as expected, sucking up lots of memory, or throwing errors. Many times these problems can be solved by building your renderer in ActionScript. Here is the source for a basic item renderer which can be scaled up as needed.

package my.renderer
{
 import my.model.DataModel;
 
 import mx.controls.Label;
 import mx.controls.listClasses.IListItemRenderer;
 import mx.controls.listClasses.ListBase;
 import mx.core.UIComponent;
 
 public class ArtListRenderer extends UIComponent implements IListItemRenderer
 {
  public function ArtListRenderer()
  {
   super();
  }
  
  
     [Bindable] public var myData:DataModel = new DataModel();
  
     // Internal variable for the property value.
     private var _data:Object;
     
     // Make the data property bindable.
     [Bindable("dataChange")]
     
     // Define the getter method.
     public function get data():Object {
         return _data;
     }
     
     // Define the setter method, and dispatch an event when the property
     // changes to support data binding.
     public function set data(value:Object):void {
         _data = value;
         
         myData = new DataModel();
         myData.firstname = value.firstname;
         myData.lastname = value.lastname;
                 
         invalidateProperties();
         dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
     }
     
     private var hBox:HBox;
     private var firstnameLabel:Label;
     private var lastnameLabel:Label;
     
     override protected function createChildren():void
     {
      super.createChildren();
      
      hBox = new HBox();
      
      firstnameLabel = new Label();
      lastnameLabel = new Label();
      hBox.addChild( firstnameLabel );
      hBox.addChild( lastnameLabel );
      
     }  
     
     override protected function commitProperties():void
     {
      super.commitProperties();
      
      hBox.horizontalScrollPolicy = 'off';
      hBox.verticalScrollPolicy = 'off';
      
      hBox.percentWidth = 100;
      
      firstnameLabel.text = myData.firstname;
      lastnameLabel.text = myData.lastname;
     }
     
     override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
     {
      super.updateDisplayList(unscaledWidth,unscaledHeight);
      hBox.move(0,0);
      hBox.setActualSize( (unscaledWidth-4), unscaledHeight);
     }
 }
}

No comments:

Post a Comment

Thank you for the comments.