PDA

View Full Version : Syncing remote JSON store to localstorage store



rez
28 Feb 2011, 8:30 PM
I have infrequently changing data I would like to cache in localstroge in my app, I have seen many threads discussing this, but never any example code.

ie.

http://www.sencha.com/forum/showthread.php?119454-Go-direct-to-proxy-and-avoid-sync()-batching&highlight=localstorage+json

So AFAIK this is what has to be done

1. Store with jsonproxy
2. Store with localstorage proxy
3. Sync the two



app.models.FilterGroup = Ext.regModel("app.models.FilterGroup", {
fields: [
{name: 'name', type: 'string'},
{name: 'value', type: 'boolean'},
{name: 'id', type: 'string'}

]
});





app.stores.filterGroups = new Ext.data.Store({
autoLoad: true,
model: 'app.models.FilterGroup',
proxy: {
type: 'ajax',
url: 'http://localhost:3000/filter_groups',
reader: { type: 'json' },
afterRequest: function() { syncToLocal(); }

},

});






app.stores.localFilterGroups = new Ext.data.Store({
model: 'app.models.FilterGroup',
proxy: {
type: 'localstorage',
id : 'filterGroup'
}

});





var syncToLocal = function() {
app.stores.localFilterGroups.clearData();

app.stores.filterGroups.each(function(rec){
// app.stores.localFilterGroups.add(rec);
app.stores.localFilterGroups.insert(rec);
app.stores.localFilterGroups.sync();

});


};




I can successfully insert (or add ) record to localFilterGroups, but syncing fails

any tips?

rez
1 Mar 2011, 1:45 PM
re:

Local storage only handles key-value pairs as strings, not objects. Stringify (http://hacks.mozilla.org/2009/06/localstorage/) can help work around that.


-----


The docs state "The LocalStorageProxy uses the new HTML5 localStorage API to save Model data locally on the client browser. HTML5 localStorage is a key-value store (e.g. cannot save complex objects like JSON), so LocalStorageProxy automatically serializes and deserializes data when saving and retrieving it."

grundlebug
1 Mar 2011, 2:55 PM
Yeah, I realized that after I posted, hence the deletion. /:)

I know it doesn't help your question, but thanks for turning my on to the localStorage proxy.

Bucs
16 Mar 2011, 6:58 AM
I am having a simliar issue...but even more straight forward. I cannot seem to delete anything from the localStorage store that I created, yet I can add items to it just fine.

I have tried:


ds.remove(rec);
ds.removeAt(int);

and even natively like so:
localStorage.removeItem('key');


Only way I can remove anything from there is to use Chrome to delete an item, and then manually adjust the counter and the main key.

But localStorage.clear() does in fact remove everything. Have you made any progress on why sync() is not working to send deletions to the underlying localStorage object from the the store?

thomasqbrady
3 Apr 2012, 4:56 AM
You need to call sync() after removing an item from localstorage.