zoukankan      html  css  js  c++  java
  • 基于backbone.js使用localstorage来缓存请求的json数据。

    基于backbone和zepto用户缓存json请求数据,

      基本作用是:增加localstorage存储中转;

      后台数据--》localstorage-》页面。。

      每次数据去localstorage取,然后把后台数据更新到localstorage里面


    用到的库:zepto.js和Backbone.js,当然稍微改一下就不需要基于这2个库的,我就直接张贴来了。懒得改了

    (function($){
    
    	
    	 var getValue = function(object, prop) {
    
    	    if (!(object && object[prop])) return null;
    
    	    return _.isFunction(object[prop]) ? object[prop]() : object[prop];
    
    	  },
    	  isCache = true,
    	  requestSteps= [];
    	  
    	  try {
    		  localStorage.setItem('cache','test');
    		} catch (e) {
    			isCache = false;
    	  }
    
    
    		
    		
    
    	var Store = $.localStorage = function(name, uptime) {
    
    		  var minutes = 1000*60;
    
    		  this.name = name;
    
    		  this.uptime= ((typeof (+uptime)==='number' && uptime > 0 && uptime  ) ||  1500) * minutes;
    		  var store = localStorage.getItem(this.name);
    
    		  this.data = (store && JSON.parse(store)) || {};
    
    		},
    
    		vessels = {},
    		myStore;
    
    		
    
    		_.extend(Store .prototype,{
    
    
    			  // Save the current state of the **Store** to *localStorage*.
    			  save: function() {
    
    //				  console.log(this.name,'中更新了来自 ',decodeURIComponent(_.map(this.data,function(val,key){return key})[0]),'的缓存数据');
    			    localStorage.setItem(this.name, JSON.stringify(this.data));
    			  },
    
    			  // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
    			  // have an id of it's own.
    			  create: function(model) {
    			    //if (!model.id) model.set(model.idAttribute, guid());
    				model.__time= Date.now();
    
    			    this.data[model.__id] = model;
    			   // $.cookie(model.__id, this.name+Date.now() , {expires: date});
    			    
    			    this.save();
    			    return model;
    			  },
    
    			  // Update a model by replacing its copy in `this.data`.
    			  update: function(model) {
    				 model.__time= Date.now();
    			    this.data[model.__id] = model;
    			    this.save();
    			    return model;
    			  },
    
    			  // Retrieve a model from `this.data` by id.
    			  find: function(id) {
    				var model= this.data[id],
    					time= Date.now(),
    					uptime= this.uptime;
    
    					return $.isObject(model) && (typeof (+model.__time) ==='number') && (time - model.__time < uptime) ? model : false;
    			  },
    
    			  // Return the array of all models currently in storage.
    			  findAll: function() {
    			    return _.values(this.data);
    			  },
    
    			  // Delete a model from `this.data`, returning it.
    			  destroy: function(model) {
    			    delete this.data[model.__id];
    			    this.save();
    			    return model;
    			  }
    
    
    		});
    
    		
    
    		
    
    		var sync= function(method, model, options){
    				var options = options ? _.clone(options) : {},
    					url= options.url, 
    					success= options.success, 
    					id, 
    					resp, 
    					ajaxtime = 500,
    					setTime = null,
    					self = this;
    
    				
    
    				
    				
    
    				if(!url){
    
    					url= getValue(model, 'url');
    
    				}
    
    				
    
    				id= encodeURIComponent(url);
    
    				//将success添加一段代码将起保存在localStorage里面
    
    				options.success = function(resp, status, xhr) {
    
    			        resp.__id= id;
    		        	myStore.create(resp);
    
    		        	//执行backbone fetch定义的success
    
    			       	success.apply(options , arguments);
    
    			    };
    
    			   
    
    			  $.later(function(){
    				  
    				    if(id && $.isObject(resp= myStore.find(id)) ){
    				    	//修改正在请求的ajax的success方法,仅保存到localStorage里面
    
    				    		options.success = function(resp, status, xhr){
    
    				    	       	resp.__id= id;
    						       	myStore.create(resp);		
    				    		}
    
    //			    			console.log('读取自缓存数去');
    
    						    success.call(options , resp, 'success' , null);
    
    				    }
    
    				    
    
    			    	Backbone.sync.call(self, 'read', self, options);
    		
    
    			  },10);
    		}
    
    		
    
    	$.sync= function(name,date){
    		if(isCache){
    			myStore= vessels[name] || (vessels[name]= new Store(name, date));
    			return sync;
    		}else{
    			return function(method, model, options){
    				 Backbone.sync.call(this, method, this, options);
    			}
    		}
    	}	
    	
    
    	 
    
    	
    
    	  
    
    })(Zepto);
    

      使用方法很简单:

    1 var collection =new Backbone.Collection.extend({
    2     sync : $.sync('zhangnan',100)//参数1保存在localstorage里面的key值,参数2过期时间
    3 });
  • 相关阅读:
    QT:浮动的饼状统计图(自绘不规则窗口)
    在QTableView中使用各种自定义委托
    QT:使用“状态模式”绘制界面
    Linux IO控制命令生成
    C++ new和delete实现原理——new和delete最终调用malloc和free
    Qt中如何 编写插件 加载插件 卸载插件
    QT:用QSet储存自定义结构体的问题——QSet和STL的set是有本质区别的,QSet是基于哈希算法的,要求提供自定义==和qHash函数
    两种方法:VS2008下C++窗体程序显示控制台的方法——在QT程序中使用cout和cin
    把自定义控件集成到Qt Designer中
    关闭Windows 2008下面应用程序出错后的提示
  • 原文地址:https://www.cnblogs.com/webzhangnan/p/2774266.html
Copyright © 2011-2022 走看看