在嵌套模板中更新特定模板

时间:2013-10-02 13:15:23

标签: backbone.js backbone-views

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

2 个答案:

答案 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();
}