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


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


It might make the most sense to override Backbone's sync() method to cover saving and editing as well. If you are using 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 didn't try this out, but hopefully you get the idea. Don't forget to define a localStorage property on your models and collections.

链接地址: http://www.djcxy.com/p/67080.html

上一篇: backbone.js模型在成功获取后不会更新

下一篇: 在主干中覆盖获取方法