假设我已经构建了一个 MainView(一个列表),它使用四个 Backbone 模型填充了一个集合。然后,对于集合中的每个模型,我根据每个模型中的数据呈现一个 SubView(一个列表项)。忽略这种嵌套视图结构是否最佳,我将如何在每个子视图(列表项)上创建一个单击事件,以启动一个引用用于创建它的模型的新视图?
我在下面的代码中粗略地(在某种程度上)做了我想做的事情:
var MainView = Backbone.View.extend({
initialize: function(){
this.render();
//fetch data into a collection
this.collection.fetch().then(function(){
this.subRender();
});
//view now has a list with four list items based on four models
},
events: {
"click li": 'newView'
},
newView: function(){
//retrieve the model from the clicked li
//close the current view, then
var newView = new NewView({model});
}
render: function(){
//create an unordered list element
this.$el.html('<ul id="list"></ul>');
},
subRender: function(){
//for each model in the collection create a new subview
var subView = new SubView({model: model}); // x 4 times
}
});
var SubView = Backbone.View.extend({
el: '#list',
render: function(){
//create an <li> with the passed-in model
//append it to the list
},
});
编辑:LosTechies有一个帖子处理这个问题,我终于找到了......