How to get the id when I create a save a new model

By : js999
Source: Stackoverflow.com
Question!

In my Marionette.CompositeView it will be possible to create a new model making a put request to the server(1).
The put request is ok, but when I add the new model to the collection, the new model misses the id which is created by the server.
How should I fix this issue?

Should
1) the POST request send the id to the client or
2) I have to make another request from the client to get the id?


(1)

return Marionette.CompositeView.extend({

    submitForm: function (event) {
            this.textAreaElement = this.$el.find('[data-tid="announcement"]');
            this.messageModel = new MessageModel();
            this.messageModel.save({
                message: this.textAreaElement.val()
            }, {
                wait: true,
                success: this.onSuccess,
                error: this.onError
            });
   },

    onSuccess: function () {
        console.log(this.messageModel.get('id')); // undefined
        this.collection.add(this.messageModel); // I need to get also the id of the following model
                                                // which is created by the server
    }

});
By : js999


Answers

In the options you pass to save() add wait:true. The attributes of the model (including id) will then be set to whatever json object the server returns for this request.



Backbone->Create and of course, like @Robert said, you can add wait:true so that your view is not updated until the server sends back your model (including the ID)



Your server needs to respond to the POST with JSON representing the saved model, including the ID (or just the the ID). For example, return {"id": "123"} and backbone will update the model for you.



This video can help you solving your question :)
By: admin