Monday, May 19, 2008

Showing Attributes with For Each

So I have been working further with my development frameset and adding attributes to the object that I am building to control social bookmarking on a web page. There are over 24 different attributes and I may have to add more. I'd like to see what they all are when I run a test and I'd like the flexibility to see any new ones I add without having to add new code to the testbed.

As it turns out, its not actually that hard to do with current JavaScript (though early versions of JavaScript didn't support this).

I have added a DIV block to the page called "showattrs" and that's where I'm going to drop the output of this little script.
<div id="showattrs"></div>

Then I've written a simple function that accepts an object as its parameter and uses the for each loop to go through the elements within the object.

function showattrs(theObject) {
var out="<pre>"
for (var attr in theObject) {
out+=attr+":"+ theObject[attr]+"\n"
}
out+="</pre>"

var block = document.getElementById("showattrs")
block.innerHTML=out
}

This works with objects or associative arrays -- which are essentially the same thing in JavaScript. Now I just call this function after I make my changes and update my display.
showattrs(sclSociaLink)

I added the pre tag to it to make the text monospaced just because its my preference for codey stuff.

Now, I know its called a for each loop, but the word "each" doesn't actually show up when coding this (it does in some other languages). The line
for (var attr in theObject)
can be read as
for each attr in theObject
I think its important to be able to read code in english. It helps to clarify thinking and makes debugging much easier. By the way, if you don't already know, var is just for making the variable attr a local variable.

So this will show all the attributes and in some browsers it will also show the code to any methods you have defined for your object. In all browsers it shows them in order of definition. So as a rule I define my methods after my attributes. This makes sure that I will see the attributes first, and then the methods.

Also, this is a cool spelling error capture. How often have you typed object.attrivute instead of object.attribute. It just happens. Well if you have done this you will now notice that attrivute is within the list. I just copy it (copy so I don't mistype again) and the do a global search on my code to find where I made my mistake.

Happy coding.

No comments: