CTLELE/script/cache.js

126 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
*缓存在文件系统中
*/
(function(window) {
var u = {};
var cache_key = "APP_CACHAE";
/**
* 存入缓存
* true: 开启同步
* false: 异步
*/
u.put = function(key, value, sync) {
var caches = {};
if (sync == "undefined" ? false : sync) {
//同步返回结果:
var caches_str = api.getPrefs({
sync: true,
key: cache_key
});
if(caches_str){
caches = JSON.parse(caches_str);
}
caches[key] = value;
api.setPrefs({
key: cache_key,
value: caches
});
}else {
api.getPrefs({
key: cache_key
}, function(ret, err) {
if(ret) {
var caches_str = ret.value;
if(caches_str) {
caches = JSON.parse(caches_str);
}
caches[key] = value;
api.setPrefs({
key: cache_key,
value: caches
});
} else {
console.log("存入缓存失败: " + JSON.stringify(err));
}
});
}
};
/**
* 取出缓存
* 同步请求
*/
u.get = function(key) {
//同步返回结果:
var caches_str = api.getPrefs({
sync: true,
key: cache_key
});
// console.log("type:"+typeof caches_str);
if(""==caches_str){
console.log("没有缓存");
return caches_str;
}
var caches = JSON.parse(caches_str);
var _cache = caches[key];
if(!_cache) {
_cache = "";
console.log("不存在key为["+key+"]的缓存");
} else {
// console.log("key: ["+key+"], value: "+_cache);
}
return _cache;
}
/**
* 清除指定缓存
*/
u.clear = function(key) {
console.log("清除指定缓存:"+key);
//同步返回结果:
var caches_str = api.getPrefs({
sync: true,
key: cache_key
});
if(caches_str) {
var caches = JSON.parse(caches_str);
if (caches.hasOwnProperty(key)) {
delete caches[key];
api.setPrefs({
key: cache_key,
value: caches
});
console.log("已删除["+key+"]");
}else {
console.log("无法清除key为["+key+"]的缓存因为不存在此key");
}
}
};
/**
* 清除所有缓存
*/
u.clearAll = function(){
api.setPrefs({
key: cache_key,
value: '{}'
});
console.log('清除缓存成功');
}
/**
* 打印所有缓存
*/
u.print = function(){
var caches_str = api.getPrefs({
sync: true,
key: cache_key
});
console.log(caches_str);
}
/* end */
window.$cache = u;
})(window);