0

我正在尝试渲染嵌套视图。说我有视图 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>

我从 调用 render bigView,它使一切都很好,包括它的 children smallViews

如何在smallView不渲染的情况下单独更新(渲染)a bigView

4

2 回答 2

1

我建议您不要view从模板代码中调用方法。我会将 smallview 的render代码移动到 bigviewrender方法。

如下所示:

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;
  },
});

这是一个小提琴smallView,它显示了它在重新渲染的事件处理程序中的作用。

于 2013-10-02T15:33:42.590 回答
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();
}
于 2013-10-02T13:21:33.560 回答