javascript - Fetch models from JSON.file and store it localstorage Backbone -
collection.fetch().done(function(){ console.log(collection); // fetchs models , print here collection.localstorage = new backbone.localstorage('localstorage'); console.log(localstorage); // storage {length: 0} });
the above code fetch data .json file , create models , prints in console.log.
but have store in localstorage, when print localstorage in console shows empty.
what want on page load data .json file using , store these models in localstorage , next time fetch data( i.e. models) localstorage not file.
you'll need override collection's sync
function place in logic first check cache fetch remote location , update cache subsequent requests pickup cache.
var collection = backbone.collection.extend({ sync: function(method, collection, options) { var cache, data, dfd = $.deferred(), cacheid = "collectioncache"; switch (method) { case "read": // attempt cache cache = sessionstorage.getitem(cacheid); // check if cache has if (cache) { console.log("returning cache"); // if cache exists, call success callback , resolve deferred object options.success(cache); dfd.resolve(cache) } else { console.log("returning external data"); // perform ajax call here fetch our json data = externaldata // set data came file our session storage sessionstorage.setitem(cacheid, data); // call success callback , resolve deferred object data loaded file options.success(data); dfd.resolve(data); } break; } // overriding sync function collection, have define logic create, update , destory methods. return dfd.promise(); } });
keep in mind, when override sync method of model or collection, have write logic handle other methods used such create
, update
, , destroy
.
more information sync
method can found in backbone's docs
i've put fiddle demonstrate functionality. http://jsbin.com/hazimi/1/edit?js,console
Comments
Post a Comment