在 jQuery 中,如何為 DOM 物件擴充私有資料,又不與既有屬性衝突,是一個關鍵設計問題。本文解析 jQuery 的資料存取機制,並提供可運行的模擬程式碼。
為 DOM 物件擴充的私有資料,可以用一個物件來表示,多個資料則用這個物件的多個屬性來存。為了能透過 DOM 物件找到這個擴充資料物件,又不與現有屬性衝突,jQuery 用一個名為 expando 的常量來表示擴充屬性的名稱,而這個 expando 的值是動態計算出來的。
舉例來說,我們可以定義 expando 的值為 "jQuery1234",然後為每個 DOM 物件加上這個屬性,屬性值是一個鍵(例如 1000)。接著在 jQuery 物件的 cache 上,會有一個名為 1000 的成員,它引用的物件就是 1000 號 DOM 物件的私有擴充物件,該物件的私有資料都存在這個物件上。
當某個 DOM 物件需要存取擴充資料時,先透過它的 expando 屬性取得鍵值,再用這個鍵值到 jQuery.cache 中找到自己的擴充物件,最後在擴充物件上讀寫資料。
// 擴充數據的屬性名,動態生成,避免與已有的屬性沖突
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.cache = {};
jQuery.expando = expando;
// 數據管理,可以針對 DOM 對象保存私有的數據
jQuery.fn.data = function (key, value) {
if (value === undefined) {
return jQuery.data(this[0], key);
}
else {
this.each(
function () {
jQuery.data(this, key, value);
}
);
}
}
jQuery.fn.removeData = function (key) {
return this.each(function () {
jQuery.removeData(this, key);
})
}
// 為元素保存數據
jQuery.data = function (elem, name, data) {
var id = elem[expando], cache = jQuery.cache, thisCache;
if (!id && typeof name === "string" && data === undefined) {
return null;
}
if (!id) {
id = ++uuid;
}
if (!cache[id]) {
elem[expando] = id;
cache[id] = {};
}
thisCache = cache[id];
if (data !== undefined) {
thisCache[name] = data;
}
return typeof name === "string" ? thisCache[name] : thisCache;
}
// 刪除保存的數據
jQuery.removeData = function (elem, name) {
var id = elem[expando], cache = jQuery.cache, thisCache = cache[id];
if (name) {
if (thisCache) {
delete thisCache[name];
if (jQuery.isEmptyObject(thisCache)) {
jQuery.removeData(elem);
}
}
} else {
delete elem[jQuery.expando];
delete cache[id];
}
}
// 檢查對象是否是空的
jQuery.isEmptyObject = function (obj) {
for (var name in obj) {
return false;
}
return true;
}
// 數據操作
$("#msg").data("name", "Hello, world.");
alert($("#msg").data("name"));
$("#msg").removeData("name");
alert($("#msg").data("name"));
透過 expando 動態屬性名加上 cache 字典的設計,jQuery 得以在干擾最小的前提下,為每個 DOM 物件保存並讀取私有資料,這是它資料方法(data / removeData)背後的核心機制。