我是一个Backbone noob,我现在已经停顿了两天,无法弄清楚我哪里出错了。谁能帮助我?
我的应用正在检索包含其中组件列表的JSON文件。每个组件都有一个它所属的类别。我创建了一个名为“Components”的视图,它是一个可折叠列表。单击组件类别时,应该打开它以显示该类别中的组件。这些组件中的每一个(列表项)都是一个名为“组件”的单独视图。
我在父视图中使用了很多append(),我认为这不是有效的。我试图编译一个html字符串,然后在一个语句中将其附加到视图,但子视图的事件没有触发。
这里可能会发生一些错误。尽管我的子列表项应该包含在ul中,但它们并不存在。如果有人能让我走上启蒙之路,那我真的很感激!
这是我的代码
/* ----------------- PARENT VIEW ---------------------- */
var ComponentsView = Backbone.View.extend({
id: 'components-view',
className: 'components-view',
html: [
'<div class="panel panel--components">',
'<h3 class="panel__heading">add an item</h3>',
'<ul class="component-list"></ul>',
'</div>'
].join(''),
initialize: function(){
var types = [];
var currentTypeSelected = 1;
this.getTypes = function(){
return types;
}
this.getCurrentTypeSelected = function(){
return currentTypeSelected;
}
this.setCurrentTypeSelected = function(value){
currentTypeSelected = value;
}
if(this.collection.length){
this.collection.each(function(model){
var thisItemType = model.attributes.type;
if(types.indexOf(thisItemType)==-1){
types.push(thisItemType);
}
});
}
this.$el.html(this.html);
this.$componentList = this.$('.component-list');
this.render();
},
render: function(){
var that = this;
this.getTypes().forEach(function(type){
that.$('.component-list').append('<li class="component-type"><a href="#">' + type + '</a>');
// now cycle through all the componenets of this type
that.$('.component-list').append('<ul>');
that.collection.byType(type).each(function(model){
that.$('.component-list').append('<li class="component">');
that.$('.component-list').append(that.renderIndividualComponent(model));
that.$('.component-list').append('</li>');
});
that.$('.component-list').append('</ul>');
});
},
renderIndividualComponent: function(model){
var componentView = new ComponentView({model: model});
return componentView.$el;
},
events: {
'click .component-type': 'onOpenSubList'
},
onOpenSubList: function (e) {
alert('open sub list');
}
});
/* ----------------- SUB (list item) VIEW ---------------------- */
var ComponentView = Backbone.View.extend({
tagName: "li",
className: "component",
initialize: function(model){
this.render();
},
render: function(){
var html = '<a href="#">' + this.model.attributes.description + '</a>'//template(this.model.attributes);
$(this.el).append(html);
return this;
},
events: {
'click a': 'onAddComponent'
},
onAddComponent: function (e) {
e.preventDefault();
alert('add component');
}
});