在创建新模型时将模型url与集合url关联

Associating a model url with the collection url while making a new model

本文关键字:url 模型 关联 集合 创建 新模型      更新时间:2023-09-26

我正在尝试创建一个新模型并将其保存在服务器上。我的问题是,当我做model.save(obj),它抛出一个错误A "url" property or function must be specified

我已经在集合中指定了一个url,我希望使用它。

我的代码:
 class TestModel extends Backbone.Model
    initialize: ->
      return;
 module.exports = TestModel

 class TestCollection extends Backbone.Collection
    model: TestModel
    url: '/models'
    parse :(response) ->
        return response.data
    addModel : (data)->
        newModel = new TestModel(data)
        newModel.save()
        @add(newModel)
module.exports = new TestCollection()

我像这样调用addModel函数

Tests = require 'path/to/test collection'
Tests.addModel(data)

抛出错误A "url" property or function must be specified

如果我修改我的addModel函数如下,它工作!:

addModel : (data)->
        newModel = new TestModel(data)
        @add(newModel)
        newModel.save()

我做错了什么?我想在save()

之后将模型添加到集合中

您得到A "url" property or function must be specified错误,因为它在这一行失败

你最后的代码工作,因为模型添加到集合有引用model.collection,所以在这种情况下save方法可以解析url。要使您的初始代码工作,您应该像下面这样为您的模型提供urlRoot:

class TestModel extends Backbone.Model
   urlRoot: '/models'
initialize: ->
   return;
 module.exports = TestModel

根据文档:

如果你使用集合之外的模型,指定一个urlRoot,以启用默认的url函数来基于模型id生成url。"urlRoot/id"