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

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!


This entry was posted on Wednesday, February 20th, 2008 at 10:04 pm and is filed under Dojo Cookies. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Even more dojo.forEach() - string as a callback”

  1. sos Says:

    Cool - I’ve stuck up a lot of these kind of tips on a post here - http://shaneosullivan.wordpress.com/2008/02/15/functional-programming-with-dojo-quick-tips


Leave a Reply

You must be logged in to post a comment.