July 17th, 2008
AS3 – My Fav Functions – hasOwnProperty()
I need to blog code samples more. To be quite frank, I don't because something in my brain always tells me my posts have to be polished and verbose and I'm always short on time. That's probably why I have a bunch of unfinished drafts sitting in my wordpress db. That being said, I'm going to attempt to short circuit my brain to allow me to post quick snippets and as a result hopefully quicker and more useful blog posts...we'll see how it goes.
So, here's the first attempt. Earlier this week a colleague of mine asked if there was a cool way to E4X filter on attributes without having them cause an RTE. The RTE would be generated in the case of nodes that don't contain the attribute.
Here's a sample block of XML:
-
<stuff>
-
<item id="1"/>
-
<item id="2" someAttrib="hello world"/>
-
<item id="3"/>
-
</stuff>
We want to filter based on @someAttrib, but when you use the E4X predicate filtering syntax, the app will RTE on the first node since it doesn't contain @someAttrib. Due to the RTE, what my colleague was doing was surrounding his code in a Try/Catch as the following example illustrates:
-
try
-
{
-
return p_item.( @someAttrib == "hello world" ).toXMLString();
-
}
-
catch( e:Error )
-
{
-
trace( "doh! I broke" )
-
}
My colleague knew there was a better way, since he knows Try/Catch can very slow. So he posed the question. I answered quickly since I got to promote one of my favorite functions in AS3: hasOwnProperty(). Here's the revised code block:
-
if( p_item.hasOwnProperty( "@someAttrib" ) )
-
{
-
return p_item.( @someAttrib == "hello world" ).toXMLString();
-
}
Enjoy!














July 17th, 2008 at 10:46 am
or you can simply say
[code]
return p_item.attribute("someAttrib");
[/code]
July 17th, 2008 at 10:53 am
Oh, I see what you’re trying to do… here are two one lines way to get the same result.
p_item.item.( hasOwnProperty(”@someAttrib”) ).toXMLString()
or
p_item.item.( attribute(”someAttrib”).length() > 0 ).toXMLString()
July 17th, 2008 at 1:06 pm
Not sure about performance implications but you can also use the following syntax and it will not throw RTEs:
myNode.(attribute(”someAttrib”) == “hello world”).toXMLString()
July 17th, 2008 at 5:00 pm
I was just about to post the same thing Ben did. It’s one of those semi-obscure things about E4X that should be more well known, but isn’t. I had someone point it out to me on my blog too.
There are other useful functions too: child(), children(), elements(), decendants(), comments()… Check the docs for more.
July 22nd, 2008 at 2:47 am
@[ Guojian, Ben, Josh ]
You all are rockin’ the additional tips, it’s always good to see other ways of doing things!
I also made sure to forward these other snippets onto my colleague.
Thanks again!
-Jun