我正在尝试渲染嵌套视图。 说我有BigView和SmallView的视图
<script type="text/template" id="big-template">
<% _.each(smallViews, function (smallView) { %>
<%= smallView.$el.html() %>
<% }); %>
</script>
<script type="text/template" id="small-template">
<div>
<%- name %>
</div>
</script>
我从bigView
调用渲染,它渲染一切正常,包括其子smallViews
。
如何在不渲染smallView
的情况下单独更新(渲染)bigView
?
答案 0 :(得分:1)
我建议您不要从模板代码中调用view
方法。我会将小视图的render
代码移到bigview render
方法。
如下所示:
var BigView = Backbone.View.extend({
render:function() {
for (var i=0;i<this.collection.length;i++) {
var smallView = new SmallView({model:this.collection.at(i)});
this.$el.append(smallView.render().el);
}
return this;
}
});
然后是您的SmallView
:
var SmallView = Backbone.View.extend({
template:_.template($('#smallTemplate').html()),
render:function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
这是一个fiddle,它会在smallView
上显示一个事件处理程序,以便重新呈现。
答案 1 :(得分:0)
只需调用render
对象的正确定义的smallView
方法即可。例如,像这样的东西。
// smallview file
var SmallView = Backbone.View.extend({
// some other methods
template: _.template($("#small-template").html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
// where you need to update the nested views
_.each(smallViews, function(smallView {
smallView.render();
}