Sunday, April 24, 2016

How to update UI from backbone cached response in titanium

Leave a Comment

I am trying to introduce cache to backbone fetch function in Titanium alloy. I have managed to cache the response and fetch the object back from cache but still did not succeed on the Backbone side of updating the UI without doing a request to the API.

I was able to replicate behavior on a web browser but seems like things differ a bit on Titanium Alloy.

Here is the code for my collection/model, precisley when if(resp) is valid

exports.definition = { config: {     "URL": "http://example.com/best-sellers/",     "adapter": {         "type": "restapi",         "collection_name": "best_sellers",          "idAttribute": "id"     },     "headers": {          "Accept": "application/json"     }, },       extendModel: function(Model) {           _.extend(Model.prototype, {});     return Model; }, extendCollection: function(Collection) {     _.extend(Collection.prototype, {         initialize: function() {             this.cacheKey = "bestSellers";             this.cacheTimeout = 1200;         },         fetch: function(options) {             // Fetch resp from cache             var resp = Ti.App.Cache.get(this.cacheKey);              // Check if cache was not empty             if (resp) {                 // Options if not set                 options = options || {};                 // Copy success method                 var success = options.success;                  options = _.extend({parse: true}, options);                  var collection = this;                 options.success = function(resp) {                     var method = options.reset ? 'reset' : 'set';                     collection['reset'](resp, options);                     if (success) success.call(options.context, collection, resp, options);                     collection.trigger('sync', collection, resp, options);                 };                 // ---> What should I be calling here to update the UI without doing a request to the API             } else {                  // The cache object doesn't hold the required data                 // Preparing success method that set the cache                  var success = options.success || function() {};                 var that = this;                 options.success = function(entity, resp, options) {                     Ti.App.Cache.put(that.cacheKey, resp, this.cacheTimeout);                     if (success) success(entity, resp, options);                 };                 // Calling the original fetch                 return Backbone.Collection.prototype.fetch.call(this, options);             }         }     });     return Collection; }       

};

Thanks for the help in advance

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment