jQuery在去除缓存数据的一个失误
来源:Ruby's Louvre 时间:2009-12-14 20:40:00
如果独自放着jQuery做事,它绝对做得很好,但jQuery充许与其他库共存在,有些事就防不胜防了。看下面代码
data :function (elem, name,data){
//略
},
removeData: function (elem, name) {
elem = elem == window ? windowData : elem;
var id = elem[expando];
// If we want to remove a specific section of the element's data
if (name) {
if (jQuery.cache[id]) {
//★★★★★★★
// Remove the section of cache data
delete jQuery.cache[id][name];
// If we've removed all the data, remove the element's cache
name = "";
for (name in jQuery.cache[id])
break;
if (!name) jQuery.removeData(elem);
//★★★★★★★
}
// Otherwise, we want to remove all of the element's data
} else {
// Clean up the element expando
try {
delete elem[expando];
} catch(e) {
// IE has trouble directly removing the expando
// but it's ok with using removeAttribute
if (elem.removeAttribute) elem.removeAttribute(expando);
}
// Completely remove the data cache
delete jQuery.cache[id];
}
},
留意星号包围的区域,John Resig的想法是,如果把元素节点的对应的缓存体的键值对全部移除后,就把此缓存体从cache中去掉。举个通俗的例子,cache就是一家银行,页面上的元素节点(elem)就是一个个人,每个人可以通过data方法在银行里开个帐户(id),而存折就是elem的那个expando属性,这个帐户可以做存许多东西,每样东西都分开管理的,如果帐户里面的东西都取光就会自动注销这个帐户。嗯,本来就应该这样,没用的东西就应该收CG回收掉,节省内存。
下面是一个仿制品
但如果jQuery与一些在Object原型进行了扩展的库共库呢?假设在它里面添加了个aa属性……
这时就无法清除缓存体了,遇到这篇文章提到的问题《Google Closure: 糟糕的JavaScript》,真是百密一疏!这也很好的教训了我们不要对Object.prototype这个最基本的东西做扩展,Prototype最近的版本也对此做了修正。那么如何排除干扰呢?