batch: function(el, method, o, override) {
// 让 el 始终为 HTMLElement
el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el);
if (!el || !method) {
return false;
}
// 确定返回的对象
var scope = (override) ? o : window;
// 看起来是个 HTMLElement 或者不是 Array
if (el.tagName || el.length === undefined) {
return method.call(scope, el, o);
}
var collection = [];
for (var i = 0, len = el.length; i < len; ++i) {
collection[collection.length] = method.call(scope, el[i], o);
}
return collection;
},小马补充
batch 是 YUI Dom 库的核心之一。它最大的意义在于,它让 Dom 库的其他大多方法
的第一个参数可以是一个 id / 元素对象 或 一组 id/元素对象,减少了循环的使用。在这里可以找到 call 与 apply 的用法。在了解了 batch 以后,下来看 YUI.util.Dom 是怎么使用这一方法的,一口气看两个函数
getStyle: function(el, property) {
// toCamel 函数后面介绍
property = toCamel(property);
// 获取节点的样式
var f = function(element) {
return getStyle(element, property);
};
return Y.Dom.batch(el, f, Y.Dom, true);
},setStyle: function(el, property, val) {
property = toCamel(property);
// 设置节点的样式
var f = function(element) {
setStyle(element, property, val);
};
Y.Dom.batch(el, f, Y.Dom, true);
},有关这两个函数的具体用法,可以看下相关的文档。其实从参数上就很容易理解怎么使用。看上面的两个函数有利于理解 YAHOO.util.Dom.batch 的调用方式。