在stories.json
我有:
[
{
id: '1',
project_id: '2',
current_state: 'finished',
description: 'Description 1'
},
{
id: '2',
project_id: '2',
current_state: 'finished',
description: 'Description 2'
},
]
这是我的Backbone应用程序示例:
(function($){
var Item = Backbone.Model.extend({
defaults: {
id: '1',
project_id: '2',
current_state: 'finished',
description: 'Description'
}
});
var List = Backbone.Collection.extend({
url: 'stories.json',
model: Item
});
var ListView = Backbone.View.extend({
el: $('body'),
events: {},
initialize: function(){
_.bindAll(this, 'render', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here
this.collection = new List();
this.collection.fetch();
this.render();
},
render: function(){
var self = this;
$(this.el).append("<ul></ul>");
console.log(this.collection)
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
},
appendItem: function(item){
$('ul', this.el).append("<li>"+ "ID: " +item.get('id')+" "+item.get('description')+"</li>");
}
});
var listView = new ListView();
})(jQuery);
我应该在哪里以及如何将Backbone中的stories.json数组展平以获取List集合?
答案 0 :(得分:0)
var ListView = Backbone.View.extend({
...
initialize: function() {
this.collection.on('reset', this.render, this);
}
...
});
var // create collection
list = new List(),
// create view
listView = new ListView({
el: $('body'),
collection: list
});
list.fetch();