Wednesday, May 20, 2009

Dojo Templated, Part IIa

Just remembered this while writing the last post, but it merits its own post:

I mentioned earlier that the arguments to a widget that can be passed with attributes are limited to those that are already fields on the object. What I didn't realize then, and which has caused me a great deal of trouble previously, is that the parsing of those arguments depends on what the default value is!

Say that we have a widget like this:
dojo.declare("swadesh.languagePicker", [ dijit._Widget, dijit._Templated ], {
templatePath: dojo.moduleUrl('swadesh', 'templates/languagePicker.html'),
languages: [],
loadDelay: 10,
title: 'language',
hook: null,
postConstruct: function() {
console.log("Title: " + this.title + " hook: " + this.hook
+ " languages: " + this.languages.toSource() + " delay: " + this.loadDelay);
}
...


It allows four arguments to be passed with a dojoType style declaration, but they'll be handled very differently. The languages parameter is parsed as a list, so you can say '[1,2]' and it will be an actual list. The loadDelay is parsed as a number, so anything that doesn't parse as a number will become NaN. The title is parsed as a string, so no further evaluation is done. The hook is parsed as raw JavaScript and evaluated! Let's see this happen:
loadDelay="13.3" title="a.b(1+3)"
hook="'swadesh'.substr(3,3)">

When this HTML is loaded, it will give the following output on the console:
Title: a.b(1+3) hook: des languages: ["danish", "english"] delay: 13.3

It that not nifty? It would appear that the scope of the hook argument evaluation is the global Dojo scope, rather than the scope of, say, the object whose template is being evaluated. That might make sense just in terms of keeping track of who's initialized when, but it's a mite impractical to not be able to refer to one's own values.

I realize now that I ran into this several months ago and had a hell of a time figuring out why I got errors out of my string arguments. Now I know that had I specified an empty string instead of null as the default, it would just have worked. Tricky!

This little find is probably going to help me quite a bit here and there. Dojo is full of little surprises that seem odd at first, but turn out to be very powerful.

No comments:

Post a Comment