Fluidbyte
Fluidbyte

Reputation: 5210

Custom Backbone Sync

I'm trying to build a custom replacement of Backbone's sync with something like the following:

function getStuff(){
    return {"id":"1","name":"Joe"};
}

Then for Backbone.sync I have:

Backbone.sync = function(method, model, options) {

    switch(method){

        case 'read':
            getStuff();
            break;

        ...More cases...

I've looked through several post on replacing sync and I know I need to use options to handle the return, but I can't seem to get it to work.

Upvotes: 2

Views: 2802

Answers (1)

Tal Bereznitskey
Tal Bereznitskey

Reputation: 2051

Fetches are usually async, so you should return your response to the options.success function:

sync : function(method, model, options) {
    if (method == 'read') {
        var yourResponse = getStuff();
        options.success && options.success(yourResponse);
    }
}

Backbone uses the options.success function to apply the response onto the Model. You can also provide your own options.success function:

yourModel.fetch({
    success : function(response) {
        // use response
    }
});

Note that Backbone will now run your custom success function and then its own function.

Upvotes: 5

Related Questions