R – AS3 Dispatch Event from Class

actionscript-3dispatcheventflash

I have a class which makes a url request and stores data from that request. When the data is retrieved, parsed, and stored into an array, I'm sending a dispatch event which I listen for in my document class. In the event handler function in the document class, I'm accessing the array that was compiled from the class. The array inside the class has 15 values, however in my event handler function, I'm only retrieving one value from it, which is the last value in the array. I posted my code below. Is there a different way I'm supposed to use the dispatchEvent in order to retrieve all of the array values instead of one?

Thanks!

Class

package com.src

{
 import flash.display.Sprite;
 import flash.net.URLRequest;
 import flash.net.URLLoader;
 import flash.events.*;
 import com.src.serialization.json.JSON;

 public class DataGrab extends Sprite
 {
  public var payload:Array;

  public function DataGrab()
  {
  }

  public function init(resource:String):void
  {
   var loader:URLLoader = new URLLoader();
   var request:URLRequest = new URLRequest(resource);
   loader.addEventListener(Event.COMPLETE, onComplete);
   loader.load(request);
  }

  private function onComplete(e:Event):void
  {
   var loader:URLLoader = URLLoader(e.target);
   var jsonData:Object = JSON.decode(loader.data);

   var people = jsonData.people;
   var names:Array = people.name;
   var counter:Number = 0;
   payload = new Array();
   for (var key:Object in names)
   {
    payload[counter] = [names[key].id, names[key].email];
    counter++;
   }
   dispatchEvent(new Event(Event.COMPLETE));
  }

  public function getResults():Array
  {
    //payload has 15 values
    return payload;
  }
 }
}

Document Class

    public function queryServer(url:String):void
    {
        grabData = new DataGrab();
        grabData.addEventListener(Event.COMPLETE, dataReadyHandler);
        resultData  = new Array();
        grabData.init(url);

    }

    public function dataReadyHandler(e:Event):void
    {
        grabData = e.target as DataGrab;
        resultData  = grabData.getResults();

            //only has 1 value, the last value in the payload array
        trace(resultData);
    }

Best Answer

the way you are handling it looks fine. I have a feeling that the length of your names array is only 1. Put a trace in a see if thats the problem.

for (var key:Object in names) 
{ 
    trace("counter",counter);
    payload[counter] = [names[key].id, names[key].email]; 
    counter++; 
} 
Related Topic