模型创建新行而不是编辑

时间:2013-07-17 10:45:52

标签: javascript backbone.js backbone-views backbone-model

我正在研究应用程序,当我创建一个组时,保存功能很好,模型被添加到集合中,并保存到数据库中,但是如果我想编辑我刚刚制作的组,我点击保存新模型已创建(和POST请求)而不是正在编辑的数据和一个PUT请求被触发。这是我的保存功能 - 有没有理由在编辑现有模型时我没有触发PUT请求?

GroupModalHeaderView.prototype.save = function(e) {
  var $collection, $this;
  if (e) {
    e.preventDefault();
  }

  $this = this;
  if (this.$("#group-name").val() !== "") {
    $collection = this.collection;
    if (this.model.isNew()) {
      this.collection.add(this.model);
    }
    return this.model.save({ name: this.$("#group-name").val()}, {
      async: false,
      wait: true,
      success: function() {
        var modelID = $this.model.get('id');

        return this.modal = new app.GroupModalView({
          model: $this.collection.get(modelID),
          collection: $this.collection
        });
      }
    });
  }

};

这是我的模型默认值,

Group.prototype.defaults = {
  user_id: "",
  name: "New Group",
  email: "",
  url: "",
  telephone: "",
  mobile: "",
  fax: "",
  people: ""
};

这是this.model之前的console.log,保存之前,

    Group {cid: "c116", attributes: Object, _changing: false, _previousAttributes:    Object, changed: Object…}
        _changing: false
        _events: Object
        _pending: false
        _previousAttributes: Object
        email: ""
        fax: ""
        mobile: ""
        name: "New Group"
        people: ""
        telephone: ""
        url: ""
        user_id: ""
        wait: true
        __proto__: Object
        attributes: Object
        changed: Object
        cid: "c116"
        collection: GroupCollection
        id: 189
        __proto__: ctor

1 个答案:

答案 0 :(得分:1)

Backbone.js触发POST请求而不是PUT的原因是因为您的模型没有与之关联的唯一标识id。如果没有与您的模型关联的id属性, Backbone.js将始终触发POST请求以将新条目保存到db。

来自骨干网站:

  

save model.save([attributes],[options])...如果模型是新的,

     

如果模型已经存在,则保存将是“创建”(HTTP POST)   在服务器上,保存将是“更新”(HTTP PUT)。

阅读this SO question了解详情。

相关问题