Reputation: 11289
i am new to backbone.js and i am trying to make a simple model work with a restful API but i cant seem to make the simple POST operation work.
from what i understand if a model element does not have the property "id" set and the save() function is called, the model will issue a post command to the server (the url of the model) and will need to receive back an HttpStatus.OK (200) and the new id of the item.
here is the JS code:
this.model = new MYAPP.menuItem(); this.model.save(); console.debug("the new id is:", this.model.get("id")) <-- this is undefined
i am using spring controller as the server side. this is the controllers code
@RequestMapping(value = "/menuItem",method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK ) @ResponseBody public Long addmenuItem(Model model) { return new Long(1); }
The Post call is reaching the server ok and the controller is called but as you can see the id of the model is not beeing updated.
what am i doing wrong?
thanks.
Additional code as requested:
initialize: function() { console.debug("initializing new view"); this.model = new MYAPP.Event(); this.model.save({ success: function( model ) { console.log( model.get('id') ); } }); var source = $("#index-template").html(); this.template = Handlebars.compile(source); console.debug("view collection", this.model); this.model.on('all', this.render, this); //this.recipes.fetch(); },
sorry for the mess!.
Upvotes: 0
Views: 844
Reputation: 44629
.save()
method is asynchronous. As so, the id
isn't returned by the server right away. Try it like this:
var self = this;
this.model.save().done(function() { console.log( self.model.get('id') ); });
edit As you have trouble with reference to your object, you can have the same result this way around:
this.model.save({
success: function( model ) {
console.log( model.get('id') );
}
});
edit after some chat Seems like the returned data wasn't valid. After a save, the server should return the full object encoding with json (with the id).
Upvotes: 2