前端数据缓存(一)
说到缓存一般针对后台缓存数据,提高数据查询效率,减少响应时间。不过在前端开发中也会遇到一些需要缓存数据的时候,比如说存储页面查询条件翻页数据、全局变量等,如果小的数据可以存储在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()。
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30