简体   繁体   中英

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM