[{"uniqueId":61,"content":"test","createTextDate":"time"}]
这是/data/commentList.json
var Comment = Backbone.Model.extend({
defaults: {
uniqueId: null,
createTextDate: null,
content: null
}
});
Backbone Collection模型
var List = Backbone.Collection.extend({
model: Comment,
url: function() {
return '/data/commentList.json';
},
parse: function(response) {
return response.results;
},
sync: function(method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url(),
processData: false
}, options);
return $.ajax(params);
}
});
Backbone Collection
var ListView = Backbone.View.extend({
el: $('#test'),
initialize: function() {
_.bindAll(this, 'render');
this.collection = new List();
this.render();
},
render: function() {
var self = this;
this.collection.fetch({
success: function() {
console.log("SUCESS");
console.log(that.collection.toJSON());
},
error: function() {
console.log('Failed to fetch!');
}
});
}
});
控制台日志
Failed to fetch!
如何使用jSON url制作Backbone Collection?
答案 0 :(得分:2)
parse: function(response) {
return response.results;
},
以上代码假定您的服务器返回
{"results": [comment1, comment2]}
您很少需要覆盖sync
方法。