javascript - 模型创建新行而不是进行编辑

标签 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

最佳答案

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

来自 Backbone 站:

save model.save([attributes], [options]) ... If the model isNew, the

save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

阅读this SO question了解更多信息。

关于javascript - 模型创建新行而不是进行编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17697708/

相关文章:

页面加载时的 JavaScript 加载屏幕

javascript - 解析 JSON 文件并存储到 Backbone 集合中,错误 : __ is undefined

javascript - 用于登录和注销功能的 Backbone.js 架构

javascript - 单击页面上的任意位置运行 Javascript 代码(单击某些 div 除外)

javascript - 如何在单击的元素正下方显示详细信息 div/弹出框

javascript - 你能在 TypeScript 类中设置静态枚举吗?

javascript - 在 Backbone 中,您是否在实例化之前定义模型的属性?

javascript - 当我从 JS 渲染模板时,主干 this.el 和事件不起作用

javascript - View 不监听模型事件 Backbone.js

javascript - 什么是事件循环,它与使用其他模型有何不同?