Search code examples
javascriptbackbone.jsbackbone-events

Update backbone model on click event and wait for response before changing location


I would like to update a backbone model when a user clicks a link. The code I have at the moment is:

$('a').on('click', function(){

    // prevent default
    event.preventDefault();

    var id = $this.data('id');

    // update backbone model
    var click = new ClickModel({ "id": id });
    var response = click.save();

    // alert('testing');

    if(response.status = 200)
    {
        return true;
    }
});

However, the database is not being updated before the url has changed. If I add in the alert it works. What is the best way of preventing the location change before the model save has completed?


Solution

  • From the fine manual:

    save model.save([attributes], [options])
    [...]
    save accepts success and error callbacks in the options hash, which are passed (model, response, options) and (model, xhr, options) as arguments, respectively.

    So you can wait for the server to finish by saying:

    click.save(null, {
        success: function(model) {
            // Do something interesting.
        }
    });
    

    Of course save is still an AJAX call so your "something interesting" will happen later. You can force the save to be synchronous but that's an evil thing to do your users so I won't show you how.