简体   繁体   中英

Fetch models from JSON.file and store it localstorage Backbone

Collection.fetch().done(function(){
    console.log(Collection); // fetchs all the models and successfully print here 

    Collection.localStorage = new Backbone.LocalStorage('Localstorage');
    console.log(localStorage); // Storage {length: 0}
});

The above code is to fetch the data from .JSON file and create models and even successfully prints it in console.log.

But i even have to store that in LOCALSTORAGE , as when i print localstorage in console it shows empty.

What i want is on page load get data from .json file using and store these models in Localstorage , so that next time i will fetch data( ie models) from localstorage not from file.

You'll need to override the collection's sync function to place in the logic to first check cache then fetch from the remote location and update the cache so subsequent requests will pickup the cache.

var Collection = Backbone.Collection.extend({
  sync: function(method, collection, options) {
    var cache, data, dfd = $.Deferred(),
        cacheId = "collectionCache";

    switch (method) {
      case "read":

        // Attempt to get the cache
        cache = sessionStorage.getItem(cacheId);

        // Check if the cache has anything
        if (cache) {
          console.log("Returning from cache");

          // If the cache exists, call the success callback and resolve the Deferred object
          options.success(cache);
          dfd.resolve(cache)
        } else {
          console.log("Returning from external data");

          // We would perform the ajax call here to fetch our JSON
          data = externalData

          // Set the data that came from the file into our session storage
          sessionStorage.setItem(cacheId, data);

          // Call the success callback and resolve the Deferred object with the data loaded from the file
          options.success(data);
          dfd.resolve(data);
        }
        break;
    }

    // By overriding the sync function for this collection, you would also have to define logic for the create, update and destory methods.

    return dfd.promise();
  }
});

Keep in mind, when you override the sync method of a model or collection, you also have to write the logic to handle the other methods that would be used such as create , update , and destroy .

More information about the sync method can be found in Backbone's Docs

I've also put together a fiddle to demonstrate this functionality. http://jsbin.com/hazimi/1/edit?js,console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM