Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through result objects in Flex?

I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this:

<DataTable>
    <Row>
        <text>foo</text>
    </Row>
    <Row>
        <text>bar</text>
    </Row>
</DataTable>

When the webservice result event is fired I do something like this:

for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++)
{
    if(event.result.DataTable.Row[i].text == "foo")
        mx.controls.Alert.show('foo found!');
}

This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the event.DataTable.Row object is not an error and the code subsequently breaks.

What is the proper way to loop through the HTTPService result object? Do I need to convert it to some type of XMLList collection or an ArrayCollection? I have tried setting the resultFormat to e4x and that has yet to fix the problem...

Thanks.

like image 235
mmattax Avatar asked Sep 20 '26 00:09

mmattax


2 Answers

The problem lies in this statement

event.result.DataTable.Row.length

length is not a property of XMLList, but a method:

event.result.DataTable.Row.length()

it's confusing, but that's the way it is.

Addition: actually, the safest thing to do is to always use a for each loop when iterating over XMLLists, that way you never make the mistake, it's less code, and easier to read:

for each ( var node : XML in event.result.DataTable.Row )
like image 59
Theo Avatar answered Sep 22 '26 16:09

Theo


Row isn't an array unless there are multiple Row elements. It is annoying. You have to do something like this, but I haven't written AS3 in a while so I forget if there's an exists function.

if (exists(event.result.DataTable) && exists(event.result.DataTable.Row)){
  if (exists(event.result.DataTable.Row.length)) {
    for(var i:int=0;i<event.result.DataTable.Row.length;i++)
    {
        if (exists(event.result.DataTable.Row[i].text)
        && "foo" == event.result.DataTable.Row[i].text)
            mx.controls.Alert.show('foo found!');
    }
  }
  if (exists(event.result.DataTable.Row.text)
  && "foo" == event.result.DataTable.Row.text)
      mx.controls.Alert.show('foo found!');
}
like image 43
dlamblin Avatar answered Sep 22 '26 16:09

dlamblin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!