前言:
?
上一篇:
?
深入解读jquery的数据存储相关(data)序2
?
?
上上一篇:
?
?
深入解读jquery的数据存储相关(data)开篇
?
?
正文:
?
?
本文关注一下jQuery1.4版本:
?
主要的变化:
?
1、增加了一个noData的对象:对特定的这3个标签不添加expando属性,当时觉得因为会抛错!
?
noData:{
"embed":true,
"object":true,
"applet":true
}
?
? ?带来的影响就是:
?
//多了一个变量,但是利用率就one
var emptyObject = {};
jQuery.extend({
data:function(elem,name,data){
//增加了对elem的判断
if(elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]){
//如果是指定的3个标签就返回了
return;
}
elem = elem == window ? windowData : elem;
//下面逻辑细节也有部分优化
var id = elem[expando],
cache = jQuery.cache,
thisCache;
//处理特殊情况,没有传递name
if(!name && !id){
return null;
}
//id的计算目的都是保证唯一
if(!id){
id = ++uuid
}
//判断name参数的类型
if(typeof name === "object"){
elem[expando] = id;
thisCache = cache[id] = jQuery.extend(true,{},name);
}else if(cache[id]){
thisCache = cache[id];
}else if(typeof data === "undefined"){
thisCache = emptyObject;
}else{
thisCache = cache[id] = {};
}
if(data !== undefined){
elem[expando] = id;
thisCache[name] = data;
}
return typeof name === "string" ? thisCache[name] : thisCache;
}
});
?
? ?看看fn里面的变换:
?
?
jQuery.fn.extend({
data:function(key,value){
//增加了对key参数的判断
if(typeof key === "undefined" && this.length){
return jQuery.data(this[0]);
}else if(typeof key === "object"){
//增加了处理object类型的支持,所有嘛each一下
return this.each(function(){
jQuery.data(this,key);
});
}
}
});
?
removeData的变化:
?
?
removeData:function(elem,name){
//加了一层判断
if(elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase]){
return;
}
elem = elem == window ? windowData : elem;
var id = elem[expando],
cache = jQuery.cache, //变化点1
thisCache = cache[id]; //变化点2
if(name){
if(thisCache){
delete thisCache[name];
//如果空对象了,再次调用removeData
if(jQuery.isEmptyObject(thisCache)){
jQuery.removeData(elem);
}
}
}
}
?
?
?
使用方法:
?
?
<div id="out1"></div>?
?
$('#out1').data({'job':'fe','name':'zhangyaochun_new'});
?
?

?
?
总结:
?
- 人性化地支持了key的原来单一的string类型
- 对特定的3个标签不处理数据存储
- 作用域链优化:将频繁出现的jQuery.cache变量化cache,而且增加了一个变量thisCache?
?
?
?