Pherrymason
Pherrymason

Reputation: 8078

Backbone: Handle server response on create

I have a view which handles a form.
This form has an event that fires up on click save button:

var FormView = Backbone.View.extend({
    initialize : function(options){
        this.collection = new PlayerCollection( {url:options.url} );
        this.collection.bind('add', this.addPlayer);
        this.collection.bind('reset', this.addAllPlayers );
    },
    saveNewPlayer : function(event){

        this.collection.create({
        name :    this.$form.find('input[name="name"]').val(),
        });
    }
});

(I've ommited some code not needed for this example).

This code saves correctly the new model, sending the data to the server and creating the View associated with this new model. But I wonder how one handles server response when POSTing data to it.
For example, how I handle if server couldn't save the data or any other kind of error is found?

I'm new to backbone and I've been using jQuery since now to code my applications, so I'm used to use success and error callbacks $.ajax offers.

Upvotes: 2

Views: 1384

Answers (1)

Jens Alm
Jens Alm

Reputation: 3057

Backbone offers similar callbacks, added as a second option hash to the create (and fetch and save) command, like this:

this.collection.create({
    name :    this.$form.find('input[name="name"]').val(),
},{
    error : function(model, response){},
    success: function(model, response){}
});

Upvotes: 4

Related Questions