Backbone.js local storage, downloading from upfront server

I am trying to create a mobile application using backbone.js which will be:

  • Download a list of items from the server the first time you start
  • Commit them to local storage (I use backbone-localstorage.js)
  • Be able to save list items as favorites by storing this in local storage

The application will never record data changes on the server, but only work with local storage.

I manually download data from the server and fill the collection, everything works fine, only I can not transfer the data to local storage.

I knock my head against the wall, trying to make it work. Any ideas on how to solve this problem are much appreciated. All the examples that I saw are either committed to the server or are pure local storage.

+4
source share
1 answer

A useful code example will be helpful.

I'm not sure how you download the list of items from the server on first start if you got local storage, but that is how I probably put it together.

A VERY EASY way to do this if you don’t need to return to the server to update any models during application launch, just deliver the models from the server built into the application and load them when creating your collection:

foo = new MyCollection(myJSONthatContainsAllTheModels) 

For more information, see Bootstrapping in Backbone Docs.

If you need to update periodically from the server during the whole time the application starts, then ..

Use backbone-localstorage as with one change. This means that it switches to the synchronization method and any usual functions of "selection", "save", etc. They will manage local storage. This change would have to copy the original Backbone.Sync into a new function called Backbone.ServerSync before replacing Backbone.Sync with the LocalStorage version. This preserves REST synchronization.

Then I would extend Backbone.Collection with a new function that is used to retrieve data from the server using the Backbone.ServerSync function.

It doesn't seem like base-localstorage is interfering with the collection URL properties, so you can do this quite easily.

This new collection feature, called, for example, serverfetch for clarity, would more or less be a clone of the selection, but using the Backbone.ServerSync method instead of Backbone.Sync.

After he receives a response from the server and checks it, he will call add for each model, which should transfer them to the local storage.

+5
source

Source: https://habr.com/ru/post/1384716/


All Articles