【问题标题】:Backbone collection url not defined未定义主干集合 url
【发布时间】:2015-09-10 11:33:41
【问题描述】:

我有以下 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/

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    根据我在文档中看到的内容,您应该调用

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

    【讨论】:

    • create 在这种情况下对我有用,但我不明白为什么。我在尝试同步remove 时也遇到了同样的问题,而且 afaik 没有类似的 op+sync 方法,是吗?
    【解决方案2】:

    在这种情况下,您可以使用方法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

    【讨论】:

    • 请在上面的答案中查看我的评论;如何正确使用syncremove 之类的命令?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多