PDA

View Full Version : AS3 and XML



tizius
March 18th, 2009, 07:14 PM
Hi,

I'm new to AS3. I'm just trying to fugure out how it works.

I'm loading a random quote from an xml file. No problem with it.
I want a button that refreshes the quote when pressed.

Here is my code:
******************
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, showRandomQuote);
loader.load(new URLRequest("threats.xml"));

var xml:XML;

function showRandomQuote(e:Event):void {
xml = new XML(e.target.data);
var quote:XMLList = xml.threat.person;
var allNum:int = quote.length();
var runNum:int = Math.floor(Math.random()*allNum);
perName.text = xml.threat.person.text()[runNum];
threatText.text = xml.threat.words.text()[runNum];
}

Again.addEventListener(MouseEvent.CLICK, showRandomQuote);

**********
I returns: Property data not found on flash.display.SimpleButton and there is no default value.

I've tried to convert the button "Again" to a movieclip but it doesn't work.

Any suggestion?

Thanks!

creatify
March 18th, 2009, 08:36 PM
You need to utilize a different method for the load complete handler and the button mouse handler. The error you're receiving: in the load handler, e.target ends up being reference to the loader, which contains the data property. When you click the button, reference to SimpleButton becomes your e.target, and by default simple button does not contain a data property, nor would it contain the xml.

Try this, didn't test but should work:



var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onXMLLoaded);
loader.load(new URLRequest("threats.xml"));

// you only need to set these vars once upon loading, not every time the button is pressed, so we pull them out of your function
var xml:XML;
var quote:XMLList;
var allNum:int;

function onXMLLoaded(e:Event):void {
xml = new XML(e.target.data);
quote = xml.threat.person;
allNum = quote.length();
// set the listener to the button here:
Again.addEventListener(MouseEvent.CLICK, showRandomQuote);
// set the first random quote
showRandomQuote();
}



function showRandomQuote(e:MouseEvent=null):void {
var runNum:int = Math.floor(Math.random()*allNum);
// were these working for you? if so keep it the same, or post your xml so we can peek
//perName.text = xml.threat.person.text()[runNum];
//threatText.text = xml.threat.words.text()[runNum];

/*
if your xml looks like this:
<threat>
<person>Name</person>
<words>asdfsadf</words>
<person>Name</person>
<words>asdfsadf</words>
<person>Name</person>
<words>asdfsadf</words>
</threat>
then I'd use the following:
*/
perName.text = xml.threat.person[runNum].toString();
threatText.text = xml.threat.words[runNum].toString();
}

tizius
March 18th, 2009, 10:45 PM
Thanks creatify, you pointed me in the right direction.