forEach goodness.
by Peter Higgins

This morning, I was again reminded about something I am continually forgetting and it’s worth documenting, so here goes:


Not only does dojo.forEach iterate over an array passing the element to a function each time:

var arr = ["one","two","three"];
// print one, two, three
dojo.forEach(arr,function(el){ console.log(el); });

It also passes the current index in the array (which I find uber helpful):

var arrOne = ["a","b","c"];
var arrTwo = ["one","two","three"];
dojo.forEach(arrOne,function(el,idx){
     // better than idx++
     var alt = arrTwo[idx];
     console.log(alt);
});

You can pass a named function, too. forEach automatically passes the element anyway:

var connects = [];
connects.push(dojo.connect("node","onclick",console,"log"));
// later:
dojo.forEach(connects,dojo.disconnect);

It also scopes, making “this” useful:

var foo = {
     myMethod: function(el){
        console.log(el);
     }
};
dojo.forEach(["a","b","c"],function(item){
     this.myMethod(item);
},foo);

And to top it alll off, dojo.query / dojo.NodeList has a .forEach method, which assumes scope, and otherwise
works the same (though the array is each domNode in the results:)

// add some text to all nodes class="links"
dojo.query(".links").forEach(function(n){
      n.innerHTML += " - touched ";
      dojo.connect(n,"onclick",function(e){
            conosle.log(e.target);
      });
});

Hope this helps.

Tags:

This entry was posted on Tuesday, February 19th, 2008 at 4:00 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.

2 Responses to “forEach goodness.”

  1. DojoCampus » Blog Archive » Demystifying dojo.data Says:

    [...] process you can go through to make your code more “async”-friendly. First, rewrite using dojo’s uber-cool [...]

  2. Learning Dojo | SitePen Blog Says:

    [...] (article) forEach goodness [...]

Leave a Reply

You must be logged in to post a comment.