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 的調用方式。