Posted on

ArrayCollection contains() uses your sort!

Here’s another gotcha that took me a while to realize what was wrong.

I was using an ArrayCollection to hold a collection of items. I had a custom sort applied since the items were typed objects that needed to be sorted according to certain, out-of-the-ordinary fields. In the sort method, I was comparing values and returning either -1 or 1.

return itemA > itemB ? -1 : 1;

From the docs for a compareFunction:

The method used to compare items when sorting. If you specify this property, Flex ignores any compareFunction properties that you specify in the ISortField objects that you use in this class.

The compare function must have the following signature:

         function [name](a:Object, b:Object, fields:Array = null):int

This function must return the following value:

  • -1, if the Object a should appear before the Object b in the sorted sequence
  • 0, if the Object a equals the Object b
  • 1, if the Object a should appear after the Object b in the sorted sequence

To return to the internal comparision function, set this value to null.

I decided that instead of returning 0 if they were the same, I would just let it stick it below the item. No big deal.

Later, when checking to see if an item was selected, I used the contains() method to see if an item was in the ArrayCollection. I quickly noticed that it wasn’t finding my item, even when I knew it was in the list.  Stepping through the code, and diving in to the Flex framework classes, I found that the contains() method uses the custom sort compare method to compare the item you’re looking for with the items in the list. It determines it found the item when it gets 0 back from the compare function. Since my custom compare method never returned 0, it never found the item.

Knowing this also helped me optimize the compare method for finding items.  Instead of thinking just in terms of whether one item goes before or after another item (or at the same level), I could also think about the comparisons in terms of checking to see if itemA was itemB.

Posted on

Removing column header sort lines

I recently ran into a problem that held me up for a little while, although it seemed like it would be a simple problem. After searching around and finding the solution, I found that it is actually pretty simple, just not obvious. Since it took me a while to find the answer, I thought it would be good to share my new found knowledge with the world.

Continue reading Removing column header sort lines