可以附加子视图一次电网Backbone.js的?(Possible to append subvie

2019-09-28 19:19发布

我经由服务,onReady加载JSON数据(对象的阵列),以及要在网格显示这些数据。 我具有由图所表示的每一行。

        render: function(){
            var self = this;
            (self.collection.models).forEach( function(model){
                var rowView = new RowView({model: model});
                self.$el.append(rowView.render().el);
            });                
        }

是否有可能建立子视图,并立刻把他们所有的DOM,而不是由1去1? 是否浏览器回流和重绘发生在每一个追加?

我见过的人子视图添加/孩子,但他们没有解决问题(经常访问DOM?),因为这仅仅是骨干是如何构建的所有方式?

Answer 1:

是啊,这是可以做到。 生成与jQuery的HTML元素(使用视图的tagName定义和attributes以及所有),然后追加一切了这一点。 当你完成后,换出当前this.$el用新的:

render: function(){

  // create in memory element
  var $el = $(this.tagName);
  // also get the `className`, `id`, `attributes` if you need them

  // append everything to the in-memory element
  this.collection.each(function(model){
    var rowView = new RowView({model: model});
    $el.append(rowView.render().el);
  });

  // replace the old view element with the new one, in the DOM
  this.$el.replaceWith($el);

  // reset the view instance to work with the new $el
  this.setElement($el);
}

这应该这样做。

当然,你会在屏幕上看到有点闪烁的,这取决于浏览器的速度有多快,以及如何大的变化。 但是,这应该让你在路上做你想做什么。

有关replaceWith更多信息: http://api.jquery.com/replaceWith/



Answer 2:

我觉得有一个比@德里克的回答简单的解决方案:

render : function () {

  var children = [];

  this.collection.forEach( function( model ) {

    var rowView = new RowView( { model : model } );

    children.push( rowView.render().el );

  } );


  this.$el.empty().append( children );


  return this;

}

http://jsfiddle.net/tXnTk/

在@德里克的回答在代码中的注释(标有我的意见“[JMM]:”):

render: function(){

  // [JMM]: You should already have this.el / this.$el, so there 
  // [JMM]: should be no need to mess with this.tagName, className, 
  // [JMM]: id, etc. Just store the child views in an array.

  // create in memory element
  var $el = $(this.tagName);
  // also get the `className`, `id`, `attributes` if you need them

  // append everything to the in-memory element
  this.collection.each(function(model){
    var rowView = new RowView({model: model});
    $el.append(rowView.render().el);
  });


  // [JMM]: Using replaceWith will wipe out event listener
  // [JMM]: registrations and other data associated with the
  // [JMM]: DOM element. That's why it's necessary to call
  // [JMM]: setElement() afterward. Since you already have
  // [JMM]: the DOM element and you just want to change the
  // [JMM]: content you might as well just empty it out and
  // [JMM]: append the new children.

  // replace the old view element with the new one, in the DOM
  this.$el.replaceWith($el);

  // reset the view instance to work with the new $el
  this.setElement($el);
}


文章来源: Possible to append subviews once to grid in backbone.js?