这个数据当然要通过属性来进行存取,但是,有多个属性怎么办呢?,要定义多个属性吗?,属性的名字叫什么呢?会不会与其他的属性有冲突呢?
在 jQuery 中,针对 DOM 对象扩展的私有数据可以用一个对象来表示,多个数据就使用这个对象的多个属性来表示。为了能够通过 DOM 对象找到这个扩展数据对象,而不会与其他现有的属性冲突,在 jQuery 中通过 expando 这个常量表示扩展对象的属性名,这个 expando 的值是计算出来的。而这个属性的值就是用来找到扩展对象的键值。
例如,我们可以定义 expando 的值为 "jQuery1234" ,那么,我们可以为每个 DOM 对象增加这个名为 "jQuery1234" 的属性,这个属性的值可以是一个键,例如为 1000。
在 jQuery 对象上的 cache 用来保存所有对象扩展的对象,这个对象可以看作一个字典,属性名就是键值,所对应的值就是扩展数据对象。
也就是说,在 jQuery 对象的 cache 上,将会有一个 1000 的成员,这个成员引用的对象就是 1000 号 DOM 对象的私有扩展对象。1000 号成员的私有数据将被存在在这个对象上。
当一个 DOM 对象需要取得扩展数据的时候,首先通过对象的 expando 属性取得一个键值,然后通过这个键值到 jQuery.cache 中取得自己的扩展对象,然后在扩展对象上读写数据。
实现代码如下:

/// <reference path="jQuery-core.js" />
// 常用方法
function now() {
return (new Date).getTime();
}
// 扩充数据的属性名,动态生成,避免与已有的属性冲突
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) { // #1001
// 取得元素保存数据的键值
var id = elem[expando], cache = jQuery.cache, thisCache;
// 没有 id 的情况下,无法取值
if (!id && typeof name === "string" && data === undefined) {
return null;
}
// Compute a unique ID for the element
// 为元素计算一个唯一的键值
if (!id) {
id = ++uuid;
}
// 如果没有保存过
if (!cache[id]) {
elem[expando] = id; // 在元素上保存键值
cache[id] = {}; // 在 cache 上创建一个对象保存元素对应的值
}
// 取得此元素的数据对象
thisCache = cache[id];
// Prevent overriding the named cache with undefined values
// 保存值
if (data !== undefined) {
thisCache[name] = data;
}
// 返回对应的值
return typeof name === "string" ? thisCache[name] : thisCache;
}
// 删除保存的数据
jQuery.removeData = function (elem, name) { // #1042
var id = elem[expando], cache = jQuery.cache, thisCache = cache[id];
// If we want to remove a specific section of the element's data
if (name) {
if (thisCache) {
// Remove the section of cache data
delete thisCache[name];
// If we've removed all the data, remove the element's cache
if (jQuery.isEmptyObject(thisCache)) {
jQuery.removeData(elem);
}
}
// Otherwise, we want to remove all of the element's data
} else {
delete elem[jQuery.expando];
// Completely remove the data cache
delete cache[id];
}
}
// 检查对象是否是空的
jQuery.isEmptyObject = function (obj) {
// 遍历元素的属性,只有要属性就返回假,否则返回真
for (var name in obj) {
return false;
}
return true;
}
// 检查是否是一个函数
jQuery.isFunction = function (obj) {
var s = toString.call(obj);
return toString.call(obj) === "[object Function]";
}


下面的脚本可以保存或者读取对象的扩展数据。

实现代码如下:

// 数据操作
$("#msg").data("name", "Hello, world.");
alert($("#msg").data("name"));
$("#msg").removeData("name");
alert($("#msg").data("name"));

以上就是【jQuery的实现原理的模拟代码 -2 数据部分】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论