Getting Booleans from E4X
March 13th, 2008 . by polyGeekI got stuck on a problem the other day using E4X. I was simply trying to get a Boolean value out of an attribute. It seemed to me that I could simply say:
setAutoPlayVideo( p.@autoPlayVideo );
Where autoPlayVideo is an attribute with a value of either “true” or “false”.
I expected E4X to type the variables I was using because I hadn’t needed to cast any of the attributes that were Strings or Numbers. Those all worked fine. After debugging a bit I discovered that each attribute was actually typed as XML. I’m a bit spoiled by my PXP2 class which automatically types values as Number, Boolean or String.
In the case of E4X and Booleans it was simple enough to fix once I understood what was going on. This does the trick:
var b:Boolean = ( p.@autoPlayVideo == "true" ) ? true : false;
setAutoPlayVideo( b );
Or if you’re not used to the ternary operator
var b:Boolean
if( p.@autoPlayVideo == "true ) {
b = true;
} else {
b = false
}
setAutoPlayVideo( b );












I’m a big fan of reducing boolean ‘if’s so I would reduce your ternary operation to:
var b:Boolean = p.@autoPlayVideo == “true”;
@Tim, I’m a big fan fan of readable code. :-)
I guess it’s what you’re used to. I’m trying to get better about not abbreviating the hell out of my code. I don’t want to count the number of times I’ve been burnt by the
if( someProp ) {…
kind of coding. Because if “someVar” happens to be equal to zero then you get a false. And I’m looking at the code going, damn, this should work. So I’m trying to do more
if( someProp != undefined ) {…
even though it’s SO much typing. :-)
But:
p.@autoPlayVideo == “true”
is an expression which evaluates to a boolean! So why feed that boolean to a conditional and then use it to update another boolean rather than just assigning it directly to the other boolean?
I’m with Tim on this one, I find it much more readable as he suggested…
@Kelvin, Thanks for clarifying. I wasn’t reading it correctly the first time. Totally makes since now.
How do you know that @autoPlayVideo is a Boolean and not intended to be the String ‘true’? ;-)
@bjorn, I think in most cases it would be treated as a Boolean. If not then it would be a simple matter to cast it as a String.
what if you’ve bound controls to an XML file? For instance I want to have an XML file that sets the visible property of a control to “true”. This works with properties like .text, .x and .width, but it doesn’t work for booleans like .visible
there must be a way to specify TRUE or FALSE directly using the XML???
Leave a Reply