Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone model.create not calling any callback

I have the following code to create a new model to a collection. The underlying datastore is a remote API:

        var postCreationStatus = this.model.create(newPostModel, {
            wait : true     // waits for server to respond with 200 before adding newly created model to collection
        }, {
            success : function(resp){
                console.log('success callback');
                console.log(resp);
            },
            error : function(err) {
                console.log('error callback');
                console.log(err);
            }
        });

The new model gets created, and I can confirm this from the database, but neither the success nor the error callbacks get called.

After the creation has been completed, I want to redirect the user. Redirecting prematurely kills the AJAX request, which is why it is important I use the success callback.

The server responds with a JSON response { id : 11 } and an HTTP status of 200 OK.

like image 270
xbonez Avatar asked Nov 28 '12 06:11

xbonez


1 Answers

Looking into the backbone code, I realized my call to the create() function was incorrect. The success and error callbacks needed to be within the object being passed in as the second argument, and not as a third argument. The changed, and working snippet is this:

var postCreationStatus = this.model.create(newPostModel, {
    wait : true,    // waits for server to respond with 200 before adding newly created model to collection

    success : function(resp){
        console.log('success callback');
        console.log(resp);
        that.redirectHomePage();
    },
    error : function(err) {
        console.log('error callback');
        // this error message for dev only
        alert('There was an error. See console for details');
        console.log(err);
    }
});
like image 108
xbonez Avatar answered Sep 19 '22 13:09

xbonez