coder
coder

Reputation: 10520

Backbone: calling a success with a custom sync method

I have a custom sync method in my backbone.js app. All my models call this method, but since I override success in this method, my success methods from the individual models are no longer being called. Here's what I mean - Below is my custom sync method:

app.customSync = function(method, model, options) {
    var success = options.success,
        error = options.error,
        customSuccess = function(resp, status, xhr) {
            //call original, trigger custom event
            if(con)console.log('in custom success');
            success(resp, status, xhr);
        },
        customError = function(resp, status, xhr) {
            if(con)console.log('in custom error');
            error(resp, status, xhr);
        };
    options.success = customSuccess;
    options.error = customError;
    Backbone.sync(method, model, options);
};
Backbone.Model.prototype.sync = app.customSync;

Here is an example me trying to call success from a model save:

this.model.save({
    success:function(model, response){
         if(con)console.log('this is never called');
    }
});

Does anyone know how I can still the custom sync with the custom success methods, and call success from my individual saves?

As a side note, I tried calling success msuccess in the model.save, but the msuccess was undefined in the custom sync.

Upvotes: 4

Views: 2426

Answers (1)

nikoshr
nikoshr

Reputation: 33344

The first argument to Model.save is a hash of attributes you wish to modify, the options come second and hold the success/error callbacks.

Try

this.model.save({}, {
    success: function() {
        console.log('save success');
    }
});

And a Fiddle to see this at work http://jsfiddle.net/nikoshr/XwfTB/

Upvotes: 4

Related Questions