dagda1
dagda1

Reputation: 28770

Backbone.marionette compositeview ignores the index for addItemView

I am using Backbone.Marionette's CompositeView and I want to insert a new model at index 0 of the collection and have it appear as the first view in the composite.

I have this code to insert the element:

PlansApp.Plans.collection.unshift new PlansApp.Plan data

The problem is that the CompositeView ignores the index of the newly inserted item in the collection.

in Backbone.Marionette, the appendHtml method looks like this:

  appendHtml: function(collectionView, itemView, index){
    collectionView.$el.append(itemView.el);
  },

The index argument is never used.

The newly inserted view will always be placed at the end of the composite.

How can I get it to appear at position 0?

Upvotes: 1

Views: 1337

Answers (2)

Greg Funtusov
Greg Funtusov

Reputation: 1447

The original Derick's answer is a bit dated for the current version of Marionette, and the wiki contains only an example for a collectionview.

Here's what I use for compositeviews currently:

appendHtml: (collectionView, itemView, index) ->
  $container = @getItemViewContainer(collectionView)
  if index is 0
    $container.prepend itemView.el
  else
    childAtIndex = $container.children().eq(index)
    if childAtIndex.length
      childAtIndex.before itemView.el
    else
      $container.append itemView.el

Upvotes: 0

Derick Bailey
Derick Bailey

Reputation: 72868

This is by design, due to the number of edge cases that have been identified in supporting sorted collections directly.

The index parameter was added so that developers could individually add support in their applications. There's a wiki page that shows an example of how to do this: https://github.com/derickbailey/backbone.marionette/wiki/Adding-support-for-sorted-collections


MySortedView = Backbone.Marionette.CompositeView.extend({
  // ...,

  appendHtml: function(collectionView, itemView, index){
    var childrenContainer = $(collectionView.childrenContainer || collectionView.el);
    var children = childrenContainer.children();
    if (children.size() === index) {
      childrenContainer.append(itemView.el);
    } else {
      childrenContainer.children().eq(index).before(itemView.el);
    }
  }

});

Upvotes: 3

Related Questions