【问题标题】:Backbone: Uncaught Error: A "url" property or function must be specified when saving model主干:未捕获的错误:保存模型时必须指定“url”属性或函数
【发布时间】:2015-01-30 12:32:13
【问题描述】:

我确实阅读了很多关于此特定消息的问题,但它们似乎不适用于我的情况。

我有这个模型:

app.Template = Backbone.Model.extend({
  defaults: {
    name: '',
    templateType: null,
    content: '',
    defaultOfType: false,
    createdAt: null,
    updatedAt: null
  }
});

这个集合:

var Templates = Backbone.Collection.extend({
  model: app.Template,
  url: '/templates'
});

app.Templates = new Templates();

在我的路由器中:

this.view = new app.TemplateFormView({ model: new app.Template() });

在那个观点中:

initialize: function() {
  this.listenTo(app.Templates, 'add', this.editTemplate);
  app.Templates.add(this.model);
  // rendering function, other stuff
},

saveMyTemplate: function(e) {
  e.preventDefault();

  var formData = {};
  var oldData = this.model.previousAttributes();

  $(e.target).closest("form").find(":input").each(function() {
    var el = $(this);
    formData[el.attr("id")] = el.val();
  });

  this.model.set(formData).save();
}

当我尝试保存模型时,我收到此错误:

Uncaught Error: A "url" property or function must be specified

如您所见,url 设置在集合中,模型是集合的一部分。知道为什么该模型似乎不是该集合的成员吗?

谢谢!

【问题讨论】:

  • 您在哪里以及如何执行 model.save()?
  • 当然 - 我将方法编辑到我的问题中!

标签: backbone.js


【解决方案1】:

您可能想查看model.urlRoot 参数。

如果您使用集合之外的模型,请指定 urlRoot,以启用默认 url 函数以根据模型 ID 生成 URL。 “[urlRoot]/id” 通常,您不需要定义它。注意 urlRoot 也可能是一个函数。

还要检查您对 app 和 app.Templates 的引用是否正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多