i want to override the fetch method in models as well as in collections for fetching the data from localstorage when there is no network connection.
This is a fetch function inside a collection
fetch:function(){
if(online){
return Backbone.Collection.prototype.fetch.call(this) ;
}else{
// return Backbone.Collection.fetch event - with data from localstorage
}
}
i am facing 2 problems here
a.The success nor error function are not been executed
this.collection.fetch({
success: function(data){ ... },
error: function(){ ... }
});
b. If there is no connection how do set the data to the collection so that i can access it in success function
Try something like this. $.ajax returns a promise so you should be able to 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 above example or as I prefer
this.collection.fetch().then(function() {
console.log('Successfully fetched from localstorage or server.');
});
After researching i have found the answer for problem a.
fetch:function(options){
if(navigator.onLine){
return Backbone.Collection.prototype.fetch.apply(this, options) ;
}else{
return //Trying to findout
}
}
After passing option argument to fetch function and arguments to fetch.apply we will be able to access the success function from the calling function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With