Marionette has a CompositeView that works best with nested collections. I've included the documentation and an article that discusses using it.
Rendering nested collections using Backbone.Marionette and Backbone.Relational
-
23-03-2022 - |
题
I'm trying to make a simple calendar/todo-list with Backbone.js.
I have a collection of Days that can each have multiple Todos. I would like to render each date into an unordered list containing itself an unordered list of todos. Here is my HTML :
<ul id="days-list">
<!-- #day-tpl -->
</ul>
<script id="day-tpl" type="tpl">
<h1>To-do for {{name}}</h1>
<ul class="todos-list">
<!-- todo-tpl -->
</ul>
</script>
<script id="todo-tpl" type="tpl">
{{title}}
</script>
And here is my JS so far (I have Backbone, Backbone.Marionette and Backbone.Relational included in the HTML).
Todo = Backbone.RelationalModel.extend({});
Todos = Backbone.Collection.extend({
model: Todo,
idAttribute: 'id_todo'
});
Day = Backbone.RelationalModel.extend({
relations:[{
type: Backbone.HasMany,
key: 'todos',
relatedModel: 'Todo',
collectionType: 'Todos',
reverseRelation:{
key: 'day',
includeInJSON: 'id'
}
}]
});
Days = Backbone.Collection.extend({
model: Day
});
TodoView = Backbone.Marionette.ItemView.extend({
tagName: 'li',
template: '#todo-tpl'
});
TodosView = Backbone.Marionette.CollectionView.extend({
itemView: TodoView
});
DayView = Backbone.Marionette.ItemView.extend({
tagName: 'li',
template: '#day-tpl'
});
DaysView = Backbone.Marionette.CollectionView.extend({
el: $('#days-list'),
itemView: DayView
});
$(document).ready(function(){
var days = new Days([
{
"id": 1,
"name": "Monday",
"todos": [
{
"id_todo": 1,
"title": "Learn Javascript"
},
{
"id_todo": 2,
"title": "Learn Node.js"
}
]
},
{
"id": 2,
"name": "Tuesday",
"todos": [
{
"id_todo": 3,
"title": "Learn Backbone"
},
{
"id_todo": 4,
"title": "Learn Backbone.Marionette"
}
]
}
]);
var daysView = new DaysView({collection: days});
daysView.render();
});
The Day collection displays fine (thanks to Marionette !) but I don't know how I'm supposed to render the Todo collections for each day. Any ideas ? Thanks !
EDIT : I've found a way, but I'm not sure it's the right way to do it.
I edited my DayView as follows :
DayView = Backbone.Marionette.ItemView.extend({
tagName: 'li',
template: '#day-tpl',
onRender: function(){
var $todosList = this.$el.find('.todos-list');
var todos = new Todos(this.model.get('todos').toJSON());
var todosView = new TodosView({collection: todos, el: $todosList});
todosView.render();
}
});
It does render each todo correctly under the right day, but the use of jquery find and toJSON is a code smell.
解决方案
不隶属于 StackOverflow