7

In my application I override Backbone.sync as follows:

Backbone.sync = function(method, model, options){ 
    //Some custom code

    //THIS FAILS.
    Backbone.prototype.sync.call(this, method, model, options); 
}}

My question is, how do I call the original sync method? Do I need to use this.sync instead?

Ken Hirakawa
  • 7,831
  • 10
  • 38
  • 49

4 Answers4

9

From what I understand, Backbone.sync checks to see if there is a locally defined version of sync and calls that before calling the global Backbone.sync :

(this.sync || Backbone.sync)

So, given that your Model is something like TestModel. I think you can do something like this (forgive, me this might not be the correct syntax, javascript is far from my specialty):

var TestModel = Backbone.Model.extend({ 

    "sync": function(method, model, options) { 
        //Some custom code

        Backbone.sync(method, model, options); 
    }
});

This is what I've gathered from here and here

Community
  • 1
  • 1
plainjimbo
  • 7,070
  • 9
  • 41
  • 55
  • 3
    I've used this approach before and found that it works well, especially if you need a model-specific sync. Altering Backbone.sync directly (as shown in another answer) will affect all of the models, which may not be what you need. – erturne Feb 09 '12 at 13:25
4
var TestModel = Backbone.Model.extend({ 
    sync: function(method, model, options){  
        // some code here
        return Backbone.sync(method, model, options); 
    }
});
Kees Briggs
  • 351
  • 3
  • 12
4

Try something like this, might not be the best solutions but it works:


var parentSyncMethod = Backbone.sync; //save parent method, the override
Backbone.sync = function() {
    // Your code here.
    var parentSyncMethod.apply(Backbone, arguments);
};

Hope it helps in some way

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

Backbone.prototype.sync.call won't work because sync is not defined on the prototype. Inspect the Backbone object in the console to see its structure. You'll want to either name your own method something else or save a reference to the original sync method before you override it with your own implementation.

Jimmy
  • 35,686
  • 13
  • 80
  • 98