开发者

Override Backbone.sync but save its previous functionality

开发者 https://www.devze.com 2023-04-12 21:28 出处:网络
I\'d like to override Backbone.sync but also have the original Backbone.sync functionality ru开发者_开发百科n after my additions. I guess kind of like calling super on a superclass in Java. Is there a

I'd like to override Backbone.sync but also have the original Backbone.sync functionality ru开发者_开发百科n after my additions. I guess kind of like calling super on a superclass in Java. Is there a way to do this other than copying all the previous code over?


In JavaScript, you can store any property or method in a variable. The following example will assign Backbone.sync to another variable and then at the end of your function call it with all the variables that are passed to your new Backbone.sync function.

var originalSync = Backbone.sync;
Backbone.sync = function() {
    // Your code here.
    return originalSync.apply(Backbone, arguments);
};


The answer provided by Brian Nickel above will actually override Backbone's sync method, which will affect all Backbone models. If what you had in mind is to override sync for an individual model type, you may prefer instead the following pattern (also making sure to override sync with the correct signature from the Backbone docs):

var YourModel = Backbone.Model.extend({
    sync: function(method, model, options) {
        // do your custom work here
        return Backbone.Model.prototype.sync.call(this, method, model, options);
    }
});

For more complete information about how this works, please refer to Backbone's annotated source itself. Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号