Tuesday, February 3, 2009

Flex ItemRenderers - and the case of the random renderering

I was reading through the book 'Flex 3 in Action' and I came across what seemed like a simple ItemRenderer example that I thought would be good show some people because it demonstrated what not to do, the visual consequences and then how to fix it. Except - in my testing it did not fix it.

The purpose of the blog posting is to highlight the issues and how I ultimately solved it - albeit I don't fully understand yet why it was happening. That will take a little more time.

The example was a simple one. There is a data grid with a data provider of objects and if the object has an email address show a button in the grid that the user can press to send the person an email. If the object in the dataprovider has no email address do not show the button.

This example is taken from section 9.2.3, page 190 of Flex 3 In Action.

Below is a working example from that section. In the first data grid, the ItemRenderer was incorrectly implemented just as the authors suggest. That being during creationComplete event we check the data to see if we should render the email button. This is incorrect, because Flex will reuse ItemRenderers and the creationComplete method should only be called once.

In the 'correct' version, we look for the dataChange event and then run the logic again to see if we should render the email button. However, I noticed that if I scrolled the list to the bottom, and then scrolled up via the scroll button one line at a time, the first time Mikey Mouse did not get a button. For some reason, the creationComplete was called for that ItemRenderer - even though the ItemRenderer that was there had its dataChange event called. Or at least that is how it appeared. Why this is happening I am not sure. However, to fix this problem I changed the creationComplete to call the checkEmail function just like dataChange and enhanced the error checking to make sure we cover the case where the ItemRenderer is created before the data property is set.

Now in the third data grid, you can scroll to the bottom, and then back up and see that Mikey Mouse can now still receive email...

Source can be found by clicking here

If anyone knows why the example exercise did not work, please leave a comment.