Javascript 我应该在哪里展平要在主干中收集的项目阵列?
在Javascript 我应该在哪里展平要在主干中收集的项目阵列?,javascript,json,backbone.js,collections,fetch,Javascript,Json,Backbone.js,Collections,Fetch,在stories.json上,我有: [ { id: '1', project_id: '2', current_state: 'finished', description: 'Description 1' }, { id: '2', project_id: '2', current_state: 'finished', description: 'Description 2
stories.json上,我有:
[
{
id: '1',
project_id: '2',
current_state: 'finished',
description: 'Description 1'
},
{
id: '2',
project_id: '2',
current_state: 'finished',
description: 'Description 2'
},
]
这是我的主干应用程序示例:
(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);
(函数($){
var Item=Backbone.Model.extend({
默认值:{
id:'1',
项目id:'2',
当前_状态:“已完成”,
描述:“描述”
}
});
var List=Backbone.Collection.extend({
url:'stories.json',
型号:项目
});
var ListView=Backbone.View.extend({
el:$(“正文”),
事件:{},
初始化:函数(){
_.bindAll(this,'render','appendItem');//记住:使用'this'作为当前对象的每个函数都应该在这里
this.collection=新列表();
this.collection.fetch();
这个。render();
},
render:function(){
var self=这个;
$(this.el)。追加(“
”);
console.log(this.collection)
_(this.collection.models)。如果集合不是空的,则每个(函数(项){//
自附项(项);
},这个);
},
附录项:功能(项){
$('ul',this.el).追加(“”+”ID:“+item.get('ID')+”+item.get('description')+” ”);
}
});
var listView=new listView();
})(jQuery);
我应该在哪里以及如何展平主干中的stories.json数组以获取列表集合?展平是什么意思?你想达到什么目标?ps:this.render()
应该在this.collection.fetch()
的成功回调中。否则,在从stories.json填充集合之前将调用render
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();