Гибкая сортировка вложенных ArrayCollections - PullRequest
0 голосов
/ 26 ноября 2010

У меня есть ArrayCollection, вложенная в другую. Мне нужно отсортировать дочернюю коллекцию по полю. Я попробовал следующий код. Он отлично работает для родительской коллекции, но ничего не делает для дочерней.

    // The Data 

public class Data
{
  public var value:String;
  public var otherValue:String;
  public var childrenData:ArrayCollection; // An array collection containing Data objects.
} 

// The sorting function 

private function sortData():void
{
  var records:ArrayCollection() = bla bla (init the collection with some Data objects).

  records.sort = new Sort();
  records.sort.fields = [
    new SortField('value', true, false)
  ];

  for each (var data:Data in records){
    sortChildren(data);
  }
  records.refresh();   
}

private function sortChildren(data:Data):void
{
  if (data.childrenData != null) {
    var srt:Sort = new Sort();
    srt.fields = [
      new SortField('otherValue', true, false)
    ];
    data.childrenData.sort = srt;
    data.childrenData.refresh();
  }  
}

Я не могу понять, что я делаю неправильно, поэтому была бы признательна за помощь.

Заранее спасибо,

1 Ответ

0 голосов
/ 26 ноября 2010

Я не совсем уверен, почему это происходит. Тем не менее, похоже, что sort наследуется его дочерним коллекциям ...

Можно ли отсортировать элементы в childData по value и по otherValue? В этом случае вы можете использовать IHierarchicalCollectionView для сортировки всех элементов. Взгляните на следующий пример:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" initialize="init()">

    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.collections.HierarchicalCollectionView;
            import mx.collections.HierarchicalData;
            import mx.collections.IHierarchicalCollectionView;
            import mx.collections.Sort;
            import mx.collections.SortField;

            private var records:ArrayCollection = new ArrayCollection([
                new Data("S", null, new ArrayCollection([
                    new Data(null, "R", null),
                    new Data(null, "B", null),
                    new Data(null, "L", null)
                ])),
                new Data("A", null, new ArrayCollection([
                    new Data(null, "P", null),
                    new Data(null, "O", null)
                ])),
                new Data("X", null, new ArrayCollection([
                    new Data(null, "C", null),
                    new Data(null, "F", null),
                    new Data(null, "E", null)
                ]))
                ]);

            [Bindable]
            private var hierarchicalView:IHierarchicalCollectionView;

            private function init():void
            {
                var hierarchicalRecords:HierarchicalData = new HierarchicalData(records);

                // you don't need this if your field is named 'children' which is the default...
                hierarchicalRecords.childrenField = "childrenData";

                hierarchicalView = new HierarchicalCollectionView(hierarchicalRecords);
                sortData(hierarchicalView);
            }

            private function sortData(view:IHierarchicalCollectionView):void
            {
                var x:ArrayCollection;
                view.sort = new Sort();
                view.sort.fields = [new SortField('value', true, false), new SortField('otherValue', true, false)];
                view.refresh();
            }
        ]]>
    </fx:Script>

    <s:layout>
        <s:HorizontalLayout horizontalAlign="center" verticalAlign="middle"/>
    </s:layout>

    <mx:AdvancedDataGrid designViewDataType="tree" height="80%" dataProvider="{hierarchicalView}"
                         creationComplete="event.currentTarget.expandAll()">
        <mx:columns>
            <mx:AdvancedDataGridColumn dataField="value"/>
            <mx:AdvancedDataGridColumn dataField="otherValue"/>
        </mx:columns>
    </mx:AdvancedDataGrid>
</s:Application>

Другой вариант - написать compareFunction, который сравнивает ваши объекты соответствующим образом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...