骨架js渲染parentview,而不在父模型更改时再次渲染子级

时间:2019-07-04 19:56:58

标签: backbone.js

我在带有嵌套集合的bellyjs中面临一些体系结构问题。我有模型的集合,并且在每个模型中它都可以包含与儿童模型相同的模型。所以在父视图渲染内部,我正在渲染子集合并将其dom附加到parentview。运行正常。

但是在更改父模型时,我正在重新渲染其视图,该视图导致其子视图再次渲染。但是,当父母的模式发生变化时,我不会创建孩子圈,因为孩子的收藏没有变化。我可以在不重新渲染的情况下利用儿童dom吗?有什么办法可以实现?

父查看代码:

RowView.prototype.initialize = function(options) {
      this.childCollection = options.childCollection;
      this.listenTo(this.model, "change", this.render);
}
RowView.prototype.render = function() {
        var existingControls = this.model.get("controls").toJSON();
        this.childCollection = this.model.get("controls");
        this.childCollection.bind('add', this.addOneChild, this);
        this.childCollection.bind('reset', this.resetChildrens, this);
        this.childCollection.reset(existingControls, this);
    };
   RowView.prototype.addOneChild = function(respModel) {
      view = new RowViewChildView({
        model: respModel,
        parentView: this
      });

     this.$el.find('.childrens').append(view.render().el);
    };

   RowView.prototype.resetChildrens = function(currentCollection) {
      this.$el.find(".childrens").html('');
      return this.addAllChildrens();
    };

    RowView.prototype.addAllChildrens = function() {
      return this.childCollection.each(this.addOneChild, this);
    };

我也不想放弃孩子观看事件。

预先感谢

2 个答案:

答案 0 :(得分:1)

很遗憾,我无法发表评论,因此我将创建一个答案。

我不确定您要实现的目标,因为您的render方法似乎只包含用于渲染子代的代码,而没有特定于渲染父代的代码,您是否将其遗漏了?

但是,您可以尝试具有渲染和重新渲染功能。 rerender函数将仅呈现父DOM中已更改的部分(所有位于父标记下方的部分)。

render: function () {
    //render everything below .parent
}
rerender: function () {
    //render stuff below parent-mark-up
}

HTML可能会被拆分

<div class="parent">
 <div class="parent-markup"></div>
 <div class="children"></div>
</div>

如果您确实需要呈现整个父元素并想要重用子DOM,则可以保护el然后再附加它,然后使用this.delegateEvents();确保事件再次冒泡。

通常,我会将侦听器放入初始化函数中,建议使用this.listenTo(this.childCollection,'add',this.callback);

Backbonejs: .on vs .listenTo vs .bind

最后,我建议使用像这样的模块化语法

var RowView = Backbone.View.extend({
    initialize: function(options) {}
    render: function() {}
});

更新:这是一个小提琴:https://jsfiddle.net/gs4r8k10/30/

答案 1 :(得分:0)

您可以使用jQuery detach()分离现有的子级DOM,并在父级重新渲染后再次附加它们。

如果可能是

if(this.childrenAlreadyRendered){
  // special performant rendering with detach
}

在您的render方法中。 进行了这种智能渲染。

相关问题