Flex 4: XML Literals with conditions - actionscript-3

Is there any way to do something like the following (pseudocode) in Flex:
var x:XML = <xml>
if(condition){
<tag>hello</tag>
}
</xml>;
which would return <xml><tag>hello</tag></xml> if the condition was true and <xml></xml> (or <xml/>) if the condition was false?
ADDITIONAL NOTE: I know how to append children, etc. I am looking for a way to do this in the literal expression.

I was really amazed at how simple it is, and at how powerful AS3 can be. The following actually worked:
var x:XML = <xml>{condition ? <tag>hello</tag> : ""}</xml>;

Use the appendChild method:
var sample:XML = <sample><items/></sample>;
if( condition ) sample.items.appendChild(<tag>hello</tag>);
else sample.items.appendChild( </tag> );

Related

Is there an alternative way to filter xml elements without the E4X syntax?

I am trying to compile some old actionscript code (part of flash app) to JS using Jangaroo. Jangaroo does not support the E4X syntax and it fails at things like the double-dot operator .. or the brackets filters a.(CONDITION). So I need to rewrite those portions of code using plain ActionScript.
For the double-dot operator, I used the instead the method descendants() but I could not find alternative way to write the brackets filter.
Here is the original code I had:
B = xml..destination.(#id == someId)
I wrote it now:
B = xml.descendants("destination").(#id == someId)
But I still want to remove .(#id == someId).
I am thinking of something like:
if (xml.descendants("destination").attribute("id") == someId)
{
B = xml.descendants("destination")
}
Is this possible?
So here is how I proceeded. I have not tested its functionality, but the compiler passed it.
var destinations:XMLList = null;
for each (var elm in xml.descendants("destination") )
{
if ( elm.attribute("id") == someId )
{
destinations += elm;
}
}

AS3 Call a variable from a compound string

I don't know how to explain this good, I'll do my best :p
I have this code:
public function clickeado(MouseEvent):void{
if(getChildByName("placa") == null){
addChild(info);
}
trace(MouseEvent.target.name)
switch(MouseEvent.target.name){
case "_783":
info.circuito_tf.text = _783_circuito;
info.localidad_tf.text = _783_localidad;
info.responsable_tf.text = _783_responsable;
break;
I want that the text of "info.circuito_tf.text" to be the value of the variable called "_783_circuito". It's ok. Now I have 17 more cases, so I decided to do something like this:
switch(MouseEvent.target.name){
case "_783":
info.circuito_tf.text = MouseEvent.target.name + "_circuito";
info.localidad_tf.text = MouseEvent.target.name + "_localidad";
info.responsable_tf.text = MouseEvent.target.name + "_responsable";
break;
I wish I explained well, thanks!
ps: the value of info.circuito_tf.text in the second case it's "783circuito" instead of the value of the variable
You can address a variable through a string via this syntax:
info.circuito_tf.text = this[MouseEvent.target.name + "_circuito"];
Watch out for undefined values, though.
Yes, with this syntax you don't need the switch statement at all, just make sure your movie clips all have valid names and correct variables exist and are assigned values.

Regular Expression Help AS3?

I am working on a regular expression and I need to extract two parts of an expression that is being imported through a flashvars.
//sample data similar to what comes in from the flashvars. Note that the spaces are not after the and symbol, they are there because the html strips it.
var sampleText:String = "height1=60& amp;height2=80& amp;height3=95& amp;height4=75& amp;"
var heightRegExp:RegExp = /height\d/g; //separates out the variables
var matches:Array = sampleText.match(heightRegExp);
Now I need help isolating the values of each variable and putting them in an array...For instance, 60, 80, etc. I know I should be able to write this regular expression, but I just can't get the exec expression right. Any help would be really appreciated!
sorry for not answering the question with regexes directly. I would do this:
var keyvalues:Array = sampleText.split("& amp;");
var firstkey:String = keyvalues[0].split("=")[0];
var firstvalue:String = keyvalues[0].split("=")[1];
Would that help beside the fact, that it is not using RegEx?
Neither the =, & or the ; are special characters, so I think you can use
=|&
in a split call and then the values will be in the odd indices and the height2 style names would be in the even indices.
You can use URLUtil.stringToObject()
Something like this should work:
var s:String = "name=Alex&age=21";
var o:Object = URLUtil.stringToObject(s, "&", true);
However, if you're just getting the flashvars, you should pull them from the loaderInfo of the root.
this.root.loaderInfo.parameters;

AS3 How to make a kind of array that index things based on a object? but not being strict like dictionary

How to make a kind of array that index things based on a object? but not being strict like dictionary.
What I mean:
var a:Object = {a:3};
var b:Object = {a:3};
var dict:Dictionary = new Dictionary();
dict[a] = 'value for a';
// now I want to get the value for the last assignment
var value = dict[b];
// value doesn't exits :s
How to make something like that. TO not be to heavy as a lot of data will be flowing there.
I have an idea to use the toString() method but I would have to make custom classes.. I would like something fast..
Why not make a special class that encapsulates an array, put methods in there to add and remove elements from the array, and then you could make a special method (maybe getValueByObject(), whatever makes sense). Then you could do:
var mySpecialArrayClass:MySpecialArrayClass = MySpecialArrayClass();
var a:Object = {a:3};
var b:Object = {a:3};
mySpecialArrayClass.addElement(a,'value for a');
var value = mySpecialArrayClass.getValueByObject(a);
I could probably cook up a simple example of such a class if you don't follow.
Update:
Would something like this help?
http://snipplr.com/view/6494/action-script-to-string-serialization-and-deserialization/
Update:
Could you use the === functionality? if you say
if ( object === object )
it compares the underlying memory address to see if two objects are the same reference...

AS3: How to simplify Action Script 3 Code?

Here's a example that I've to use when I want to create a button with mouse-over effect:
this.buttonExample.buttonMode = true;
this.buttonExample.useHandCursor = true;
this.buttonExample.addEventListener(MouseEvent.CLICK,myaction);
I'm new to AS3 - is there any way, to simplify this code like this:
this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction);
why does it not works ?
Its already as simple as it gets. Firstly
this.buttonExample.buttonMode = true;
this.buttonExample.useHandCursor = true;
this.buttonExample.addEventListener(MouseEvent.CLICK,myaction)
is much more readable than
this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction);
Always go for readbility over anything else. And secondly,
this.buttonExample.buttonMode = true;
does not return an object so you can't interact with anything.
If you're using that pattern a lot, you can make a helper function:
public function setAsButton(button:Sprite, clickHandler:Function):void {
button.buttonMode = button.userHandCursor = true;
button.addEventListener(MouseEvent.CLICK, clickHandler);
}
Then call it somewhere:
setAsButton(this.buttonExample, myaction);
If you feel that typing this.buttonExample over and over again is too repetitive, simply assign that object to a variable and use that variable in the rest of the statements:
var b : Button = this.buttonExample;
b.buttonMode = true;
b.useHandCursor = true;
b.addEventListener(...);
As other's have mentioned, there's also the with statement, but it's use is discouraged since it makes the code harder to read, and may lead to weird results:
with (this.buttonExample) {
buttonMode = true;
useHandCursor = true;
addEventListener(...);
}
You can, of course, combine these suggestions with other tricks, like chaining assignments:
var b : Button = this.buttonExample;
b.buttonMode = b.useHandCursor = true;
b.addEventListener(...);
Be very careful to only chain assignments in this way if the assigned value is immutable (e.g. true, false, numbers and strings, but not arrays or most other objects), because the same object will be assigned to all variables on the left side. If the value is immutable this doesn't matter, but if it's mutable you can end up with weird results, like this in this example:
a = b = [ ];
a.push(1);
b.push(2);
trace(a); // outputs 1, 2
trace(b); // also outputs 1, 2
The reason for this result is that a and b both reference the same array, and since arrays are mutable it doesn't matter how you access the object, it will still be changed. a and b don't reference different arrays just because they are different variables.
You may think that you could do something like the following, but it will not work.
// this will NOT work
var b : Button = this.buttonExample;
(b.buttonMode = b.useHandCursor = true).addEventListener(...);
The reason why it works to say b.buttonMode = b.useHandCursor = true, but not to add .addEventListener(...) is that the value of an assignment expression (e.g. b.buttonMode = true) is the value assigned to the left hand side (e.g. true). If you add .addEventListener(...) to that you are essentially saying true.addEventListener(...), which clearly is not what you want. In other words
b.buttonMode = b.useHandCursor = false;
is equivalent to
b.useHandCursor = false;
b.buttonMode = b.useHandCursor;
Which should hopefully also make the caveats mentioned above plain.
you can use the with statement. however I'd not encourage you to do so, since it leads to a lot of ambiguity and unclearness.
also, you can have multiple assignments:
this.buttonExample.buttonMode = this.buttonExample.useHandCursor = true;
this sometimes is useful, but for the sake of readability, you shouldn't overuse it.
greetz
back2dos