PUT and POST requests in Backbone.js

Sudo picture Sudo · Dec 7, 2012 · Viewed 7.1k times · Source

I have another question related to the PUT and POST requests. So, here I have a form which has the fields like : "name" and "link".

On submit of that form, I am not able to post that form to the server on doing this.model.save();

Also, how do I understand when will the model be invoking a POST and when will it invoke a PUT request? Since I dont have any "id" attribute from my api response so I dont have any id for my model too.

So how do I pass my form field value on click of the "Submit" button as a POST request?

Also, Is there a way I can invoke the request: For eg: If i hit on the "Update" button of my form, I will call a function from my model

updateModel:function(options){
this.update("update","/messages",[options])
}

or a get request can be read like this

getModel:function(options){
this.update("read","/messages",[options])
}

Answer

Andrew Hubbs picture Andrew Hubbs · Dec 7, 2012

The save method will determine whether to POST or PUT based on the return value of isNew(). This method generally just checks for an id being populated. You can override it to use some other indicator.

You pass form field values on submit directly into your save method. Something like this:

//In your view
events : {"submit" : "onSubmit"},
onSubmit : function(e) {
  e.preventDefault();
  this.model.save({name: this.$("#name").val()}, {
    success : function (newModel) { /* Do something here. */ }
  });
}

Another alternative is to use a library like Backbone.Modelbinder to handle the syncing between DOM and model for you.

You shouldn't need to define those new methods on your model. You should instead define a proper url method on the model or corresponding controller. Then you can just use the normal fetch and save methods to handle your get/updates.