Backbone.js - model.save() not firing a PUT request

Theo Alvarez picture Theo Alvarez · Jun 20, 2013 · Viewed 14.8k times · Source

I have a basic application using Backbone.js that is not making PUT calls (updating model). From the front-end, I calling a models save function doesn't make a PUT call; however, if I replace it with destroy, it does make a DELETE call to the back-end. Anyone have any idea what might be the issue? The function that is not firing a PUT request is the saveTask function.

App.Views.Task = Backbone.View.extend({
    template: _.template("<label>ID:</label><input type='text' id='taskId' name='id' value='<%= _id %>' disabled /><br><label>Title:</label><input type='text' id='title' name='title' value='<%= title %>' required/><br><label>Content:</label><input type='text' id='content' name='content' value='<%= content %>'/><br><button class='save'>Save</button>"),
    events: {
        "change input":"change",
        "click .save":"saveTask"
    },
    render: function(eventName){
        $(this.el).html(this.template(this.model.toJSON()));
        //console.log(this.generateTemplate());
        return this;
    },
    change: function(event){
        var target = event.target;
        console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value);
        change[target.name] = target.value;
        this.model.set(change);*/
    },
    saveTask: function(){
        this.model.set({
            title:$("#title").val(),
            content:$("#content").val()
        });
        if(this.model.isNew()){
            App.taskList.create(this.model);
        } else {
            this.model.save({});
        }
    }
});

Answer

Rayweb_on picture Rayweb_on · Jun 20, 2013

If your model is new, then at the time you save it it will fire a post method. If your model however is not new and you are updating it, it will fire a PUT.

if this is not working for you it may be because your model does not have an id property, in case you are using an id with a different name, for example taskID, then in your model you have to set the idAttribute to taskID so backbone uses this property as the Id and everything will be normal.

like this:

 var Task= Backbone.Model.extend({
   idAttribute: "taskId"
 });

here is the link to the documentation on Idattibute http://backbonejs.org/#Model-idAttribute

also another problem could be the {} in your save call try just

 this.model.save(); 

instead of

 this.model.save({});