Javascript 主干显示嵌套的json集合
不知道我到底哪里出了问题。我似乎无法获得模板来呈现嵌套json中的标题属性。我在网上学习一个教程,这个教程有点牵手,但是我碰到了一堵砖墙,不明白为什么它不能渲染。任何帮助都将不胜感激 这是我的模板和htmlJavascript 主干显示嵌套的json集合,javascript,json,backbone.js,Javascript,Json,Backbone.js,不知道我到底哪里出了问题。我似乎无法获得模板来呈现嵌套json中的标题属性。我在网上学习一个教程,这个教程有点牵手,但是我碰到了一堵砖墙,不明白为什么它不能渲染。任何帮助都将不胜感激 这是我的模板和html <script id="albumTemplate" type="text/template"> <p><%= title %></p> </script> <script id="subalbumTem
<script id="albumTemplate" type="text/template">
<p><%= title %></p>
</script>
<script id="subalbumTemplate" type="text/template">
<p><%= title %></p>
</script>
<div class="row">
<div class="six columns"><h5>Albums</h5></div>
<div class="six columns"><h5>Sub-Albums</h5></div>
</div>
<div class="row" style="color: #333;">
<div class="six columns" id="categories"></div>
<div class="six columns" id="sub-cat"></div>
</div>
问题是您等待来自
this.albumList.fetch()
的重置
事件,但是默认情况下不会触发重置
,因此您需要将{reset:true}
传递到获取
。这是一本书
一些附带的建议(我将选择您的AlbumCollectionView
),但您的其他视图也是如此:
el:'#categories',而不是el:$(“#categories”)
initialize
中,当您可以利用时,您正在使用此.model.on
。使用listenTo
的主要优点是,在视图上调用remove
时,事件侦听器将为您清理
// this works.
this.collection.on('reset', function () {
this.render();
}, this);
// can be written as (remember the we changed model to collection above).
this.listenTo(this.collection,'reset',this.render);
渲染
函数,一个主干。集合
有大量附加到它们上
// while this works
_.each(this.collection.models, function (album) { ... });
// can be written as:
this.collection.each(function(album) { ... });
});
$(this.el)
有点过时,您可以使用this.$el
,它只是视图元素的缓存jQuery对象app.AlbumCollectionView = Backbone.View.extend({
el: '#categories',
initialize: function () {
this.listenTo(this.collection,'reset', this.render);
},
render: function () {
this.collection.each(function (album) {
var albumView = new app.AlbumView({model: album});
this.$el.append(albumView.render().el);
}, this);
return this;
}
});
非常感谢你!这是我在stack上收到的最好、最具描述性的答案之一。这也是一个很好的奖励,因为我收到了一些关于我的代码和不同的做事方式的反馈:)不确定你是否可以帮我做更多的事情,但我正在尝试改变它的呈现顺序。我希望看到的是[Album title],然后是[children of Album title],然后是[NextAlbum title],然后是[children of Album title]等等。你的意思是这样的?如果是这样,这是因为您渲染视图的顺序。
// this works.
this.collection.on('reset', function () {
this.render();
}, this);
// can be written as (remember the we changed model to collection above).
this.listenTo(this.collection,'reset',this.render);
// while this works
_.each(this.collection.models, function (album) { ... });
// can be written as:
this.collection.each(function(album) { ... });
});
app.AlbumCollectionView = Backbone.View.extend({
el: '#categories',
initialize: function () {
this.listenTo(this.collection,'reset', this.render);
},
render: function () {
this.collection.each(function (album) {
var albumView = new app.AlbumView({model: album});
this.$el.append(albumView.render().el);
}, this);
return this;
}
});