我在 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": [] } ]
然后我有 Backbone 模型和集合:
Group = Backbone.Model.extend({
urlRoot: 'groups',
});
Groups = Backbone.Collection.extend({
url: 'groups',
model: Group
});
我想创建一个像这样的集合实例:
groups = new Groups();
groups.fetch();
但我总是收到错误:
Uncaught TypeError: Property 'url' of object [object Object] is not a function
最佳答案
试试这个
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') %>
<% }); %>
关于javascript - 指定了集合的 URL,但返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22302694/