最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call parent backbone sync method - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 17, 2012 at 4:00 Ken HirakawaKen Hirakawa 8,25110 gold badges40 silver badges49 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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

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

var TestModel = Backbone.Model.extend({ 
    sync: function(method, model, options){  
        // some code here
        return Backbone.sync(method, model, options); 
    }
});

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.

发布评论

评论列表(0)

  1. 暂无评论