Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call parent backbone sync method

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?

like image 432
Ken Hirakawa Avatar asked Jan 17 '12 04:01

Ken Hirakawa


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is backbone a MVC?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


3 Answers

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

like image 128
plainjimbo Avatar answered Sep 23 '22 07:09

plainjimbo


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

like image 25
Sudhir Bastakoti Avatar answered Sep 22 '22 07:09

Sudhir Bastakoti


var TestModel = Backbone.Model.extend({ 
    sync: function(method, model, options){  
        // some code here
        return Backbone.sync(method, model, options); 
    }
});
like image 31
Kees Briggs Avatar answered Sep 23 '22 07:09

Kees Briggs