javascriptbackbone.jsbackbone-model

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.


Solution

  • 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);
        }
    });