前不久在研究jQuery的动画队列的时候,发现jQuery的缓存系统也很强大,尽管以前也稍微接触过,但一直都没有深入研究过。jQuery的缓存系统在外部应用的时候都比较简单,比如要将某个URL数据存到缓存中只要这么写:
[url=http://jb51.net] // 将数据存到缓存对象中
thisCache[expando][val] = data;
}
// 返回DOM元素存储的数据
return thisCache[expando][val];
}
};
var removeData = function( key, val ){
if( typeof key === "string" ){
delete cacheData[key];
}
else if( typeof key === "object" ){
if( !key[expando] ){
return;
}
// 检测对象是否为空
var isEmptyObject = function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
removeAttr = function(){
try{
// IE8及标准浏览器可以直接使用delete来删除属性
delete key[expando];
}
catch (e) {
// IE6/IE7使用removeAttribute方法来删除属性
key.removeAttribute(expando);
}
},
index = key[expando];
if( val ){
// 只删除指定的数据
delete cacheData[index][expando][val];
// 如果是空对象 索性全部删除
if( isEmptyObject( cacheData[index][expando] ) ){
delete cacheData[index];
removeAttr();
}
}
else{
// 删除DOM元素存到缓存中的所有数据
delete cacheData[index];
removeAttr();
}
}
};
上面的代码值得注意的是IE6/IE7中用delete来删除自定义的属性会报错,只能使用removeAttribute来删除,标准的浏览器都可以使用delete来删除。下面是调用的结果:
var box = document.getElementById( "box" ),
list = document.getElementById( "list" );
data( box, "myName", "chen" );
alert( data( box, "myName" ) ); // chen
data( box, "myBlog", "stylechen.com" );
alert( data( box, "myBlog" ) ); // stylechen.com
removeData( box, "myBlog" );
alert( data( box, "myBlog" ) ); // undefined
alert( data( box, "myName" ) ); // chen
alert( box[expando] ); // 1
removeData( box );
alert( box[expando] ); // undefined
当然,jQuery的缓存系统比我的这个要复杂些,不过核心原理还是一样的。easyAnim将会在后续的版本中引入这个缓存系统。