Вот цель: у меня есть модель parent
. Он находится в коллекции под названием parents
. В parent
находится коллекция children
. Итак, когда я создаю экземпляр коллекции parents
, я получаю модели parent
, каждая из которых содержит коллекцию children
.
Я пытался сделать это несколькими разными способами, и я получаю разные результаты. Иногда children
вообще не появляются. Иногда они повторяются для каждой итерации цикла рендеринга parent
. Я ищу помощь в том, что лучше всего для этого.
Список children
не должен меняться, каждый раз это должна быть одна и та же коллекция. Я могу отфильтровать различия позже, на лету.
Я урезал его, чтобы он был как можно проще, чтобы просто извлекать данные, никаких других дополнений не включено, чтобы было ясно, что должно произойти.
Я загружаю коллекцию children
дважды. (Ну, много раз, но один раз в коллекции parent
и один раз в каждой модели parent
). Это сделано для того, чтобы я мог добавить нового «родителя» и иметь доступ к дочерним элементам, чтобы я мог добавить их в «родительскую» модель перед сохранением.
ВОПРОСЫ:
- Как сделать так, чтобы
Children
загружались вParent
только один раз? - Как загрузить одну коллекцию
Children
в коллекциюParents
? - Это правильный способ сделать это?
Модели:
$(function() {
window.Child = Backbone.Model.extend({});
window.Children = Backbone.Collection.extend({
model: Child
});
window.Parent = Backbone.Model.extend({
initialize: function() {
this.children = new Children();
children.fetch();
}
});
window.Parents = Backbone.Collection.extend({
model: Parent
initialize : function() {
this.childrenAll = new Children();
this.childrenAll.fetch();
}
});
// instantiate the collections
window.parents = new Parents();
});
Мои взгляды:
$(function() {
window.ChildView = Backbone.View.extend({
className: "child-item",
template: _.template($('#child-template').html()),
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
window.ChildrenView = Backbone.View.extend({
className: 'children',
template: _.template($('#children-template').html()),
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('reset', this.render);
},
render: function() {
this.$el.html(this.template());
this.collection.each(function(child) {
var view = new ChildView({ model:child });
$('.children-list').append(view.render().el);
});
return this;
}
});
window.ParentView = Backbone.View.extend({
className: "parent",
template: _.template($('#parent-template').html()),
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.children = new Children({ collection: children });
$('.children-list').html(this.children.render().el);
return this;
}
});
window.ParentsView = Backbone.View.extend({
el: "#app",
template: _.template($('#parents-template').html()),
initialize: function () {
_.bindAll(this, 'render', 'add');
this.collection.bind('reset', this.render);
},
render: function() {
this.$el.html(this.template());
this.childrenView = new ChildrenView({ collection: children });
$('.children-new').append(this.childrenView.render().el);
this.collection.each(function(parent){
var view = new ParentView({ model: note });
$('#items-list').prepend(view.render().el);
});
return this;
}
});
});
Маршрутизатор:
$(function() {
window.ParentsRouter = Backbone.Router.extend({
routes: {
'': 'list'
},
initialize: function() {
// starts by assigning the collection to a variable so that it can load the collection
this.parentsView = new ParentsView({
collection: parents
});
parents.fetch({ reset: true });
},
list: function () {
$('#app').empty();
$('#app').append(this.parentsView.render().el);
}
});
window.parentsRouter = new ParentsRouter();
Backbone.history.start();
});