指定了集合的URL但它返回错误

时间:2014-03-10 14:18:50

标签: javascript backbone.js marionette

我在myapp.com/groups上有一个像这样的集合:

[   {
    "_id": "52dd2bd1044bf96a12ed2319",
    "name": "US",
    "id": 1,
    "users": []   },   {
    "_id": "52dd2bd1044bf96a12ed231b",
    "name": "BR",
    "id": 3,
    "users": []   },   {
    "_id": "52dd2bd1044bf96a12ed231c",
    "name": "SK",
    "id": 4,
    "users": []   },   {
    "_id": "52dd2bd1044bf96a12ed231d",
    "name": "CZ",
    "id": 5,
    "users": []   },   {
    "_id": "52dd2bd2044bf96a12ed231e",
    "name": "UK",
    "id": 6,
    "users": []   } ]

然后我有骨干模型和集合:

Group = Backbone.Model.extend({
        urlRoot: 'groups',
    });

Groups = Backbone.Collection.extend({
        url: 'groups',
        model: Group
    });

我想创建一个像这样的集合实例:

groups = new Groups();

groups.fetch();

但我总是收到错误:

  

未捕获的TypeError:属性' url'对象[object Object]不是函数

2 个答案:

答案 0 :(得分:0)

正如Puigcerber所说,最可能的原因是你没有在你的网址(groups)前面添加正斜杠。 Backbone对于一些事情非常非常,而url属性就是其中之一。尝试将url集合的Groups属性更新为/groups

这可能是一个意外的Backbone.Sync覆盖,正如Rocky Lee所说的那样,但我打赌我的车是url财产激怒了Backbone众神。

答案 1 :(得分:0)

尝试这个

的javascript

var Group = Backbone.Model.extend({});
var Groups = Backbone.Collection.extend({
    model: Group,
    url: "groups",
    parse: function(data) {
        return data;
    }
});
var GroupView = Backbone.View.extend({
    el: $("#page"),
    initialize: function() {
    },
    render: function() {
        var that = this;
        this.collection = new Groups();
        this.collection.fetch({
            type: "GET",
            contentType: 'application/json',
            dataType: "json",
            success: function(collection, response) {
                var template = _.template(yourViewTemplate, {
                    groups: that.collection.models
                });
                that.$el.html(template);
            },
            error: function(collection, response) {
                alert("error");
            }
        });

    }
});

HTML

<% _.each(groups, function(group) { %>
   <%= group.get('_id') %>
   <%= group.get('name') %>
   <%= group.get('id') %>
<% }); %>