Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override fetch method in backbone

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

like image 584
Anenth Avatar asked Oct 04 '13 07:10

Anenth


2 Answers

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.'); 
});
like image 86
TYRONEMICHAEL Avatar answered Oct 07 '22 09:10

TYRONEMICHAEL


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

like image 26
Anenth Avatar answered Oct 07 '22 08:10

Anenth