Backbone可以以相反的顺序呈现集合吗?

Joe*_*Joe 7 backbone.js marionette

我正在使用Signalr集线器订阅服务器上的事件.什么事件被分派到集线器,它成功地将项目添加到Marionette CollectionView.反过来,这将呈现给一个表.

因为事件表基本上是一个吸墨纸,我希望这些事件的顺序相反,最好只保留n个事件.

Backbone可以"自动"以相反的顺序重新渲染集合吗?

Jul*_*sar 11

要按相反的顺序进行收集,我通常使用这样的结构:

_.each(collection.last(collection.length).reverse(), function(model){ });
Run Code Online (Sandbox Code Playgroud)


Ton*_*leh 8

这个主题有一个主题,网址是https://github.com/marionettejs/backbone.marionette/issues/78

虽然Backbone在定义比较器后对集合进行了排序,但正如@breischl指出的那样,Marionette在订单更改时不会自动重新呈现CollectionView.实际上,Marionette会add在集合上监听事件并添加一个新的ItemView.

如果你希望你CollectionView始终显示在反向时间顺序的项目,并希望新项目加入到被前置,而不是附加,然后覆盖appendHtml在你的方法CollectionView如下:

var MyCollectionView = Backbone.Marionette.CollectionView.extend({
  appendHtml: function(collectionView, itemView){
    collectionView.$el.prepend(itemView.el);
  }
});
Run Code Online (Sandbox Code Playgroud)

如果您希望能够在评论中提到的@dira中插入特定位置,那么在sithman的github上面的链接上发布了一个解决方案,为了方便我在这里重现(免责声明:我没有测试下面的代码亲身):

将appendHtml更改为:

appendHtml: function(collectionView, itemView) {
  var itemIndex;
  itemIndex = collectionView.collection.indexOf(itemView.model);
  return collectionView.$el.insertAt(itemIndex, itemView.$el);
}
Run Code Online (Sandbox Code Playgroud)

并添加以下内容以扩展jQuery以提供insertAt功能:

(function($) {
  return jQuery.fn.insertAt = function(index, element) {
    var lastIndex;
    if (index <= 0) return this.prepend(element);
    lastIndex = this.children().size();
    if (index >= lastIndex) return this.append(element);
    return $(this.children()[index - 1]).after(element);
  };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)


rfu*_*duk 1

通常,您将在“子类”中进行渲染Backbone.View。所以你有类似的东西:

render: function() {
  this.collection.each( function(model) {
    // some rendering of each element
  }, this );
}
Run Code Online (Sandbox Code Playgroud)

this.collection大概是一个Backbone.Collection子类,所以你可以只使用underscore.js 方法来按照你喜欢的顺序获取它:

this.collection.reverse().each( ... )
this.collection.sort( function(m) { ... } ).each( ... )
Run Code Online (Sandbox Code Playgroud)

ETC。

当然,您从后端获取单个元素,并且希望将其插入到正确的位置而不重新渲染整个元素!因此,在这种情况下,只需走老路,将排序键作为rel属性或data元素上的属性插入,然后insertAfter在您的(或类似)方法中使用它或与 jQuery 类似renderNewItem

  • 不幸的是,underscore.js 方法中没有可用的 reverse() 方法。 (2认同)