R – Flex ItemRenderer as a field of `data`

apache-flexitemrenderer

I would like to let the data provided to a DataGrid decide how best it should be rendered (that is, let the data carry with it an object which will do the rendering).

For example, by creating a "Renderable" interface, which has a 'renderer:IFactory' property, then used as below:

<mx:DataGrid x="0" y="0" width="100%" dataProvider="{myDataProvider}">
    <mx:columns>
    <mx:DataGridColumn headerText="Task" width="100"
        itemRenderer="{(data as Renderable).renderer}"/>
    </mx:columns>
</mx:DataGrid>

But to do this, Renderable has to extend IEventDispatcher, which seems like a little much…

I've also tried using:

itemRenderer="{(data as Renderable).getRenderer()}"

Which does nothing (in fact, the getRenderer method never gets called).

Is there a better way to do this? Am I doing something fundamentally wrong?

Thanks!

Best Answer

I could be wrong but I think the "data" property you're referencing in the code sample above is the "data" for the top-level Container in your view and not for that particular row of the DataGrid. A few other approaches come to mind:

  1. Implement a single item renderer class that examines the data being passed to it and utilizes the proper item renderer for the type of data supplied.
  2. Implement a function in the view of your DataGrid that examines your dataProvider and returns the proper item renderer class; call this inside the DataGridColumn.itemRenderer property using a binding expression.
  3. Implement an subclass of DataGridColumn that has the logic baked into it to set the correct itemRenderer.

I would actually recommend against mixing "renderer data" that is View-specific with data from your Model. Unless you wrap the core model data with an object that exposes it along with the renderer (what some people call a ViewModel).

Related Topic