Lucas
Lucas

Reputation: 3471

backbonejs POSTinstead of PUT on save

I'm having an issue when I try to update a task model to the database. It acts as if its a new model. I also get an error after the save that may be related? error and code are below. Is there any additional information needed?

I looked at this question related to my question but I have ensured that im using the id attribute.

Error:

Uncaught TypeError: Object function (obj) { return new wrapper(obj); } has no method 'has'
_.extend.setbackbone.js:246
_.extend.save.options.successbackbone.js:308
jQuery.Callbacks.firejquery.js:1046
jQuery.Callbacks.self.fireWithjquery.js:1164
donejquery.js:7399
jQuery.ajaxTransport.send.callback

Code:

Update: function(id) {
            console.log('Updating task');
            this.task = this.taskList.get(id);
            var new_task_name = prompt("enter new name for " + this.task.get("name"),"Default...");
            console.log('saving task ' + this.task.id +': '+ this.task.get("name") + ' isNew? -' + this.task.isNew());
            this.task.save({
                name: new_task_name
            });
            console.log('task saved ' + this.task.id +': '+ this.task.get("name") + ' isNew? -' + this.task.isNew());

            this.taskView = new TaskView({
                model: this.task
            });
            this.taskView.render();
        }

Upvotes: 0

Views: 125

Answers (2)

Lucas
Lucas

Reputation: 3471

I found the issue... The wording is swapped in the Codeigniter restful API I'm using. They handle POST as update and PUT as new.

Upvotes: 0

Chris Herring
Chris Herring

Reputation: 3665

I'm not sure what your error is. If the model has an id set then isNew() should return false. Check the 'idAttribute' on your model and that this value is set on the model.

One issue that you do have is that the save() method is asynchronous. If you want to render the TaskView when the task is saved you should add a success handler (and an error handler if it failed) e.g.

var me = this;
this.task.save({
    name: new_task_name
}, {
    success: function(task, response) {
        console.log('task saved ' + task.id +': '+ task.get("name") + ' isNew? -' + task.isNew());

        me.taskView = new TaskView({
            model: task
        });
        me.taskView.render();
    },
    error: function(model, response) {
        var errorMsg;
        // Response may be string (if failed model validation) or an AJAX response (if failed server side)
        if (_.isString(response))
            errorMsg = response;
        else
            errorMsg = response.responseText;

        // Display error
    }
});

Upvotes: 1

Related Questions