YAHOO.util.Dom.batch

I have been trying to find a YUI method that is similar to the JQuery $.each method, but the closest thing I could find for the current version of YUI is YAHOO.util.Dom.batch (YUI 3 has an ‘each’ method, but I haven’t explored it thoroughly). While this method is not as powerful as JQuery’s $.each (see example), it is still a very good replacement for a Javascript ‘for’ loop when iterating over a DOM collection.

In Javascript, to iterate over a Dom collection, I would do the following:

?View Code JAVASCRIPT
this.getFormValues = function(form, fncName) {
     var str = "";
     var fn = eval("this."+fncName);
     var nL = form.elements.length;
     for (var i = 0; i < nL; i++) {
          if (fn) {
               if (this.canSubmit) {
                    this.canSubmit = fn (form.elements[i]);
               } else {
                    break;
               }
          }
          if ((form.elements[i].type == 'radio') || (form.elements[i].type == 'checkbox')) {
               if (form.elements[i].checked) {
                    str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
               }
          } else {
               str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
          }
     }
     return str;
}

With the YAHOO.util.Dom.batch, I can do the following:

this.getFormValues = function(form, fncName) {
var str = "";
var fn = eval("this."+fncName);
YAHOO.util.Dom.batch(form.elements, function(el) {
if (fn) {
if (this.canSubmit) {
this.canSubmit = fn (el);
} else {
break;
}
}
if ((el.type == 'radio') || (el.type == 'checkbox')) {
if (el.checked) {
str += el.name + "=" + escape(el.value) + "&";
}
} else {
str += el.name + "=" + escape(el.value) + "&";
}
}
return str;
}

Although YAHOO.util.Dom.batch is not as versatile as JQuery’s $.each method, it is still a very powerful method.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks