Backbone集合URL未定义

时间:2015-09-09 19:10:43

标签: javascript backbone.js

我有以下Backbone代码,它应该用模型创建一个集合,并在其中创建一个新的模型实例,并将其保存在服务器上。

var Project = Backbone.Model.extend({});

var Projects = Backbone.Collection.extend({
    model: Project,
    url: "/api/projects"
});

var projects = new Projects();

projects.add({
    "title": "My Project"
}).sync();

但是,运行此命令时出现以下错误;

A "url" property or function must be specified

我认为该模型将继承集合as per the documentation中的url属性。为什么不呢?怎么了?

JSFiddle:http://jsfiddle.net/6L8v4dj8/

2 个答案:

答案 0 :(得分:1)

根据我在文档中看到的,你应该调用

projects.sync('create', projects.models[0]) http://backbonejs.org/#Sync

答案 1 :(得分:1)

在这种情况下,您可以使用方法create,例如:

var Project = Backbone.Model.extend({});

var Projects = Backbone.Collection.extend({
    model: Project,
    url: "/api/projects"
});

var projects = new Projects();

projects.create({
    title: "My Project"
});
  

Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model.

documentation