读jq之六(数据暂存)
jq的$.data,$.removeData方法设计的很巧妙,为增强理解模仿其写了个。都三个方法set,get,remove都挂在data对象上。
(function (){
var stamp = '$' + (new Date).getTime(), uid = 0, cache = {};
var data = {
set : function(el, name, data) {
var id = el[ stamp ], thisCache;
if (!id) {
id = ++uid;
}
if ( !cache[ id ] ) {
el[ stamp ] = id;
cache[ id ] = {};
}
thisCache = cache[ id ];
if ( data !== undefined ) {
thisCache[ name ] = data;
}
},
get : function(el, name) {
var id = el[ stamp ], thisCache = cache[ id ];
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
remove : function(el, name) {
var id = el[ stamp ], thisCache = cache[ id ];
if ( name ) {
if ( thisCache ) {
delete thisCache[ name ];
}
} else {
try{
delete el[ stamp ];
}catch(e){
el.removeAttribute( stamp );
}
delete cache[ id ];
}
}
};
window.data = data;
})();