Using an AS3 object or class as a DataProvider

I have a need to use custom class objects as a DataGrid dataprovider.  After wrestling with flash.utils.describeClass() I gave up and found two other methods for binding my custom objects to a DataGrid.

First here is a look at the sample MXML app I put together.

Using custom object as a DataGrid.dataProvider in Flex 3

Same object bound two different ways

Click here to run this demo in a new window.

In the first grid the DataGrid gets a column per object property.

var dp_horizontal:Array = ArrayUtil.toArray( myCustomObj );
grid_1.dataProvider = dp_horizontal.valueOf();

In the second grid, I run my custom object through a helper function to create an ArrayCollection containing NAME, VALUE pairs for each object property.

/**
 * Convert a class object into an ArrayCollection to be used
 * as a DataProvider
 */
private function objectToDataProvider( obj:Object ):ArrayCollection
{
	// our DataProvider
	var dp:ArrayCollection = new ArrayCollection();
	// get object class info
	var info:Object = mx.utils.ObjectUtil.getClassInfo( obj );
	// split the class property list into Array
	var propsA:Array = String( info.properties ).split(',');
	// loop over class properties grabbing value and filling up dp
	for( var xx:int = 0; xx <= propsA.length-1; xx++)
	{
		dp.addItem( { name : propsA[ xx ], value : obj[ propsA[ xx ] ] } );
	}

	return dp;
}

I’m currently using this helper function to bind the result of WebORB.NET data calls to a DataGrid for testing.  This code could really be used by any type of object though.

Hope this helps somebody else.

About Eric Fickes

Independent Internet Consultant by day. Skateboarder, Bass player, Husband and Father by night. You can hire me to build internet powered solutions
This entry was posted in adobe, flash platform, FLEX, tips and tricks and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Using an AS3 object or class as a DataProvider

  1. qqq says:

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>