木偶复合视图排序渲染

时间:2015-06-06 15:58:14

标签: backbone.js marionette backbone-views

我有一个Marionette(2.4.1)CompositeView,当我进行排序时,它重新渲染整个视图而不是childView。标题图标还原。我可以在渲染上修复它们,但有没有办法可以渲染childView?

diaryEntries = Backbone.Marionette.CompositeView.extend({
  template  : diaryEntries,
  className: 'diary-entries',
  collection: new Diary(),
  childViewContainer: 'tbody',
  reorderOnSort: true,

  events: {
    'click th[data-sort]': 'sort',
    'click .pagination a': 'paginate'
  },

  initialize: function() {
    this.itemsPerPage = 5;
    this.currentPage = 1;
    this.pages;
  },

  ...

  sort: function(e) {
    var $th, dir, sort, sorted;
    e.preventDefault();
    $th = $(e.currentTarget);
    sort = $th.data('sort');

    if (sort === this.collection.sortField) {
      this.collection.sortDirection *= -1;
    } else {
      this.collection.sortDirection = 1;
    }

    this.collection.sortField = sort;

    $('span.glyphicon').removeClass('active-sort');
    $th.siblings('th').find('span.glyphicon').removeClass('glyphicon-chevron-down glyphicon-chevron-up').addClass('glyphicon-sort');

    if (this.collection.sortDirection === 1) {
      $th.find('span.glyphicon').removeClass('glyphicon-chevron-down glyphicon-sort').addClass('glyphicon-chevron-up active-sort');
    } else {
      $th.find('span.glyphicon').removeClass('glyphicon-chevron-up glyphicon-sort').addClass('glyphicon-chevron-down active-sort');
    }

    this.collection.sort();
  },
...

});

1 个答案:

答案 0 :(得分:2)

好吧,看起来像Marionette一样关注你是一回事。我无法在文档中找到这个,但它在源代码中很明显。如果您通过此选项:

reorderOnSort: true

进入您的Collection / Composite视图,在'sort'事件中,Collection / View将不会重新呈现,只有它的子项。

请参阅Marionette来源中的这一行:https://github.com/marionettejs/backbone.marionette/blob/v2.4.1/src/collection-view.js#L166

更新如果您要过滤子视图,则对集合运行sort将在Collection / CompositeView上调用render。逻辑是,如果您将孩子的结果分页,那么您必须对原始的,未经过滤的集合进行排序,以正确显示分页结果。

尽管如此,我还没有看到任何本质上错误的分页过滤集。

幸运的是,它很容易覆盖sort方法来呈现您的结果是否被过滤。在你的Collection / CompositeView上包含这个方法:

reorder: function() {
   var children = this.children;
   var models = this._filteredSortedModels();

   // get the DOM nodes in the same order as the models
   var els = _.map(models, function(model) {
     return children.findByModel(model).el;
   });

   this.triggerMethod('before:reorder');
   this._appendReorderedChildren(els);
   this.triggerMethod('reorder');
   }
},