说到缓存一般针对后台缓存数据,提高数据查询效率,减少响应时间。不过在前端开发中也会遇到一些需要缓存数据的时候,比如说存储页面查询条件翻页数据、全局变量等,如果小的数据可以存储在cookies中,但是数据多了就不行了,下面介绍下前台缓存的简单实现:
/** * cache 类定义,cache对象在main.jsp 中定义 * @param {Object} scope * @memberOf {TypeName} * @return {TypeName} */ var BaseCache = function(scope){ this.scope = scope; this.gloableCache = this._getPrmGoableCache(); //init if(this.gloableCache){ if(this.gloableCache[this.scope] == undefined){//全局cache,所以不会重新生成cache this.gloableCache[this.scope] = {}; } } }
定义一个构造函数,不同的功能有不同的缓存,定义缓存基本方法
BaseCache.prototype = { _getPrmGoableCache : function(){ if(top===self){//topest window if(window.prmGloableCache){ return window.prmGloableCache; } }else{ var p=parent; while(p){ if(p.prmGloableCache|| p.top==p.self){ break; }else{ p=p.parent; } } if(p.prmGloableCache){ return p.prmGloableCache; } } }, put:function(key, value){ if(this.gloableCache && this.gloableCache[this.scope]){ this.gloableCache[this.scope][key] = value; } }, get:function(key){ if(this.gloableCache && this.gloableCache[this.scope]){ return this.gloableCache[this.scope][key]; } }, clear:function(){ if(this.gloableCache && this.gloableCache[this.scope]){ return this.gloableCache[this.scope] = {}; } }, clearByKey:function(key){ if(this.gloableCache && this.gloableCache[this.scope]){ delete this.gloableCache[this.scope][key]; } } };
下面举个例子来使用该缓存,比如说缓存页面查询条件:
var paramEchoCache = new BaseCache("paramEcho");
//保存form查询条件
$.fn.saveQueryParam = function(){
$(this).each(function(i){//一个页面上可能有多个form
var forms = paramEchoCache.get(window.location.href);
if(forms == undefined){
forms = {};
paramEchoCache.put(window.location.href,forms);
}
forms[$(this).attr('id')] = $(this).serializeArray();
});
}
//获取查询条件
$.fn.getQueryParam = function(){
var forms = paramEchoCache.get(window.location.href);
if(forms){
var fields = forms[$(this).attr('id')];
if(fields){
return serializeJson(fields);
}
}
return {};
}
在查询后,调用form.saveQueryParam来保存查询条件,在返回需要回显查询条件时,调用 getQueryParam()。