12

我有一个使用 Backbone.js 的基本应用程序,它不进行 PUT 调用(更新模型)。从前端,我调用模型save函数不会进行 PUT 调用;但是,如果我将其替换为destroy,它确实会对后端进行 DELETE 调用。有人知道可能是什么问题吗?未触发 PUT 请求的函数就是saveTask函数。

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({});
        }
    }
});
4

4 回答 4

20

如果你的模型是新的,那么在你保存它的时候它会触发一个 post 方法。但是,如果您的模型不是新模型并且您正在更新它,它将触发 PUT。

如果这对您不起作用,可能是因为您的模型没有 id 属性,如果您使用具有不同名称的 id,例如 taskID,那么在您的模型中,您必须将 idAttribute 设置为 taskID 所以主干使用这个属性作为Id,一切都会正常。

像这样:

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

这是 Idattibute http://backbonejs.org/#Model-idAttribute上文档的链接

另一个问题可能是您保存调用中的 {}

 this.model.save(); 

代替

 this.model.save({});
于 2013-06-20T20:44:47.227 回答
2

在我的情况下,由于验证而失败。当我保存模型时,它会验证模型的所有属性,而我用于列出接口的集合不需要模型的所有属性。

我遇到了同样的问题并在 Google 中搜索并找到了您的问题并阅读了解决方案和评论。然后我意识到在更新的主干规范中提到当 model.save() 在模型请求之前执行时,它首先调用 validate 和 if验证成功,否则它将继续失败,这就是为什么它没有在 chrome 调试器网络选项卡中显示任何网络请求的原因。

我已经为我面临的案例编写了解决方案,其他可能面临不同的问题。

于 2014-06-08T04:30:47.323 回答
2

我相信模型总是期待选项参数,也可能是回调

this.model.save(null, {
    success: function (model, response) {

        //
    },
    error: function () {
        //
    }
});

如果您查看 Backbone src,您也会注意到...

======

// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function (key, val, options) {
    var attrs, method, xhr, attributes = this.attributes;

    // Handle both `"key", value` and `{key: value}` -style arguments.
    if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
    } else {
        (attrs = {})[key] = val;
    }

    options = _.extend({
        validate: true
    }, options);

    // If we're not waiting and attributes exist, save acts as
    // `set(attr).save(null, opts)` with validation. Otherwise, check if
    // the model will be valid when the attributes, if any, are set.
    if (attrs && !options.wait) {
        if (!this.set(attrs, options)) return false;
    } else {
        if (!this._validate(attrs, options)) return false;
    }

    // Set temporary attributes if `{wait: true}`.
    if (attrs && options.wait) {
        this.attributes = _.extend({}, attributes, attrs);
    }

    // After a successful server-side save, the client is (optionally)
    // updated with the server-side state.
    if (options.parse === void 0) options.parse = true;
    var model = this;
    var success = options.success;
    options.success = function (resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = model.parse(resp, options);
        if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
            return false;
        }
        if (success) success(model, resp, options);
        model.trigger('sync', model, resp, options);
    };
    wrapError(this, options);

    method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
    if (method === 'patch') options.attrs = attrs;
    xhr = this.sync(method, this, options);

    // Restore attributes.
    if (attrs && options.wait) this.attributes = attributes;

    return xhr;
},
于 2013-06-20T23:23:04.513 回答
0

Backbone 的同步功能是我最终使用的。您必须将“更新”作为第一个参数(“方法”参数)传入。

于 2016-11-01T20:26:23.457 回答