前端数据缓存(一)

说到缓存一般针对后台缓存数据,提高数据查询效率,减少响应时间。不过在前端开发中也会遇到一些需要缓存数据的时候,比如说存储页面查询条件翻页数据、全局变量等,如果小的数据可以存储在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()。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值