Hint: Always better to use ‘itemUpdated’ method instead of ‘setItemAt’ when updating existing items in ArrayCollection

April 20th, 2008

   When you want to update already existing data item in your ArrayCollection in ActionScript 3 with a new values for object’s properties you have 2 options to select from:

  1. use itemUpdated(obj) ArrayCollection’s method.
  2. use setItemAt(obj, index) ArrayCollection’s method.

   ActionScript code sample:

    //Update an existing person in the ArrayCollection via setItemAt
 
    public function updatePersonViaSetItemAt():void {
        var currentlySelectedItem : Object = dg.selectedItem;
        currentlySelectedItem.first = firstInput.text;
        currentlySelectedItem.last = lastInput.text;
        ac.setItemAt(currentlySelectedItem, dg.selectedIndex);
    }
 
    // Update an existing person in the ArrayCollection via itemUpdated
 
    public function updatePersonViaItemUpdated():void {
        var currentlySelectedItem : Object = dg.selectedItem;
        currentlySelectedItem.first =  firstInput.text;
        currentlySelectedItem.last =  lastInput.text;
        ac.itemUpdated(currentlySelectedItem);
 
    }

   Which one to choose?

   I would strongly advice to always use ‘itemUpdated’ because of the following reasons:

  • Calling setItemAt(x) on your existing data item in ArrayCollection is an equivalent to calling the removeItemAt(x) method and then calling the addItemAt(…, x) method on your data item.
       Thus after making the call to setItemAt(x, index) you will loose the current selection in your ArrayCollection dependant UI component (mx:DataGrid, mx:Tree, mx:Combobox.. etc..)

  • If the Sort rule is already applied to your ArrayCollection then you can receive some funky results like unwanted inserting of a new row when partly changing several properties of the existing data item in ArrayCollection.

   Interactive sample with “View source” option enabled to watch the difference:
http://jabbypanda.com/labs/updateArrayCollectionItem/updateArrayCollectionItem.html

You can try the following:

  1. First apply sorting to any of the DataGrid’s column
  2. Select the first row in the Datagrid
  3. Rename the surname of the person to something completely new starting with a new letter
  4. Press “Update via setItemAt()” button control

Voilà, new unwanted row becomes visible in the Datagrid.

  • Thanks for the sample code. The adobe docs are a bit lacking.

  • deepak

    really good one , i was doing it , thank you now i got more clear ids