Override the sampling method in the trunk

I want to override the sampling method in models, as well as in collections, to retrieve data from localstorage when there is no network connection.

This is a selection function within the collection.

fetch:function(){ if(online){ return Backbone.Collection.prototype.fetch.call(this) ; }else{ // return Backbone.Collection.fetch event - with data from localstorage } } 

I ran into two problems here

a. Success or error function not executed

 this.collection.fetch({ success: function(data){ ... }, error: function(){ ... } }); 

b. If there is no connection, how to set data to a collection so that I can access it in the success function

+7
javascript
source share
3 answers

After research, I found the answer to problem a.

 fetch:function(options){ if(navigator.onLine){ return Backbone.Collection.prototype.fetch.apply(this, options) ; }else{ return //Trying to findout } } 

After passing the argument of the option to extract the function and arguments to fetch.apply, we can access the success function from the calling function

+3
source share

Try something like this. $ .ajax returns a promise so you can do the following

 fetch:function(){ var dfd = new jQuery.Deferred(); if(this.online){ return Backbone.Collection.prototype.fetch.call(this) ; }else{ // Do your logic for localstorage here dfd.resolve(); } return dfd.promise(); } 

Then you can use your example above or as I prefer

 this.collection.fetch().then(function() { console.log('Successfully fetched from localstorage or server.'); }); 
+4
source share

It may be most appropriate to override the Backbone sync () method to save and edit. If you use the local storage provided by backbone.localStorage.js, your override might look something like this:

 Backbone.sync = function(method, model, options, error) { if(navigator.onLine){ // Or, however you determine online-ness return Backbone.ajaxSync.apply(this, [method, model, options, error]); } return Backbone.localSync.apply(this, [method, model, options, error]); } 

I have not tried this, but I hope you understand this idea. Remember to define the localStorage property in your models and collections.

+1
source share