Even more dojo.forEach() - string as a callback

After Petes tasty cookie yesterday, I have a couple of more useful bites of dojo goodness.
Besides passing a complete callback to dojo.forEach() you can also use a string which gets converted into a callback function internally, this is pretty handy for mini tasks.

dojo.forEach([1,2,3,4], "console.log(item, index, array)");

This prints the item, the index and the array for each element. So you can see already all the power. You have three variables available that you can use in this string “item”, “index” and “array”. Using this notation for source code longer than a line might not be a good idea.

Setting the right scope

You can even do some nifty things with it, that would otherwise result in a couple of lines.

dojo.forEach(nodes, 'dojo.connect(item, "onclick", "onClickHandler", this)', this);

And the scope is given as another parameter. So it calls the method “onClickHandler” from the scope the dojo.forEach() is in.
Quite handy I would say.

There is a tricky thing, since the scope is being passed inside the callback and can be accessed via “this” you might also end up with strange constructs like this:

var x = 3;
dojo.forEach([1,2,3,4,5], 'if (item==this) console.debug(item)', x);
// prints: 3

The scope passed into the callback (the second parameter passed to dojo.forEach) “x” can be referred to inside the string as “this”. That looks a little strange, but it allows this short hand notation to access the current scope.

Have fun forEach-ing!

Tags: