Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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({});
        }
    }
});
like image 526
Theo Alvarez Avatar asked Jun 20 '13 20:06

Theo Alvarez


1 Answers

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({});
like image 118
Rayweb_on Avatar answered Sep 20 '22 09:09

Rayweb_on