forked from jeromegn/Backbone.localStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackbone.localStorage-min.js
5 lines (5 loc) · 1.54 KB
/
backbone.localStorage-min.js
1
2
3
4
5
/**
* Backbone localStorage Adapter v1.0
* https://github.com/jeromegn/Backbone.localStorage
*/
function S4(){return((1+Math.random())*65536|0).toString(16).substring(1)}function guid(){return S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()}window.Store=function(a){this.name=a;var b=localStorage.getItem(this.name);this.records=b&&b.split(",")||[]},_.extend(Store.prototype,{save:function(){localStorage.setItem(this.name,this.records.join(","))},create:function(a){return a.id||(a.id=a.attributes.id=guid()),localStorage.setItem(this.name+"-"+a.id,JSON.stringify(a)),this.records.push(a.id.toString()),this.save(),a},update:function(a){return localStorage.setItem(this.name+"-"+a.id,JSON.stringify(a)),_.include(this.records,a.id.toString())||this.records.push(a.id.toString()),this.save(),a},find:function(a){return JSON.parse(localStorage.getItem(this.name+"-"+a.id))},findAll:function(){return _.map(this.records,function(a){return JSON.parse(localStorage.getItem(this.name+"-"+a))},this)},destroy:function(a){return localStorage.removeItem(this.name+"-"+a.id),this.records=_.reject(this.records,function(b){return b==a.id.toString()}),this.save(),a}}),Backbone.localSync=function(a,b,c,d){typeof c=="function"&&(c={success:c,error:d});var e,f=b.localStorage||b.collection.localStorage;switch(a){case"read":e=b.id!=undefined?f.find(b):f.findAll();break;case"create":e=f.create(b);break;case"update":e=f.update(b);break;case"delete":e=f.destroy(b)}e?c.success(e):c.error("Record not found")},Backbone.ajaxSync=Backbone.sync,Backbone.sync=Backbone.localSync;