簡體   English   中英

可以將子視圖一次附加到grid.js中的網格嗎?

[英]Possible to append subviews once to grid in backbone.js?

我正在通過服務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,而不是一一對應? 瀏覽器是否會在每個附加項上進行重排和重繪?

我已經看到了人們添加子視圖/子視圖的所有方式,但是它們都不能解決問題(頻繁的DOM訪問?),因為這正是骨干網的構建方式?

是的,可以做到。 使用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/

我認為有一個比@Derick的答案更簡單的解決方案:

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/

@Derick答案中的代碼注釋(我的注釋標記為“ [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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM