JavaScript Gotchas

This just cost me and a colleague about an hour.

  var headers = mydiv.getElementsByTagName('h3');
  for (var i = 0; i < headers.length; i++) {
    // ...

When run, this wasn’t going inside the for loop at all (in IE; firefox worked). So we stuck in an alert to see what headers.length came out as. [object] apparently.

After much chasing around the houses, we looked closer at the original HTML:

  <h3 id='length'>Some Header</h3>

It’s a miracle that this worked at all in firefox. What was happening is that the length property of the headers collection was being shadowed by the element with an id of length. That’s happening because the collection is an HTMLCollection, and the JavaScript DOM bindings specify that you can also index by id into that collection. And because functions and properties share the same namespace in JavaScript, disaster ensues.

So the lesson to take away from all this is that you should take great care to avoid using id’s that are the same as existing method or property names. Eric Meyer found the same things some time ago: Reserved ID Values.


XML::Genx Plans

I was talking to Mark Fowler yesterday and XML::Genx came up. He had a couple of good points:

  • It’s not absolutely clear in the documentation that any valid Perl string will work correctly (be it UTF-8 encoded or not). I need to double check the tests for this and amend the docs.
  • The API is still fairly horrible. It mirrors the C api almost exactly, but this feels very odd as a Perl programmer. I need to have a think about what would be better. Ideally, I’d like something more like ruby’s builder. In fact, I actually wrote something similar to that before (XML::SAX::Builder), but that uses SAX, which is too slow in Perl.

I really appreciate the feedback. Apart from Aristotle, it’s the only feedback I’ve had since I released it.

If I can figure these out, I should probably slap a 1.0 on it.

I also reckon I should do a talk on “Why we need another XML writer”. There are quite a few on CPAN already and I should say why I wrote another one…