Trunk (Marionette also) trying to display a new entry at the beginning of the collection, without re-rendering the entire collection

I am trying to display an item at the beginning of the collection (imagine if you are posting a new post to facebook)

When I came to add (answer, {at: 0}); in the collection, the record is correctly inserted at 0 in the collection, but is displayed at the bottom of the list of elements. I am confused since I worked on this before, but I think that what I did in the hacker style was just reset and re-rendering the collection.

I am wondering if this is a great way to handle this, and where should I bind the logic.

Is this a method of adding a collection? This is currently empty (but I'm using Marionette), and I feel like it overrides the default rendering. How can I manage this again, so I can correctly add my new item to the list without destroying it and not creating it.

+7
source share
2 answers

In Marionette, the standard way to add a new item to a collection in views is to use the jQuery append method. The CollectionView type has an appendHtml method that is used to actually add. (see http://derickbailey.github.com/backbone.marionette/docs/backbone.marionette.html#section-24 )

You can easily override this method in your specific collection view, and attach a new model wherever it is.

In your case, if you always want to add a new model to the top of the list, it’s very simple to change the look of the collection to do this:

 Backbone.Marionette.CollectionView.extend({ appendHtml: function(cv, iv){ cv.$el.prepend(iv.el); } }); 

Notice that cv is an instance of the collection view, and iv is an instance of the element view for the model in the collection.

If you need to do more complex things, for example, find the exact position in an existing collection of HTML nodes, you can do this in the appendHtml function appendHtml . Of course, this becomes more difficult than just preend instead of append, but it is still possible.

Hope this helps.

+12
source

This may be a very old question, but I will lay out my solution anyway ... It adds / adds an itemViewContainer with new models depending on how they were added to the collection (unshift / add), overriding the appendHtml function.

 appendHtml: function(collectionView, itemView, index){ if(index > 0) { collectionView.$el.find(this.itemViewContainer).append(itemView.el); } else { collectionView.$el.find(this.itemViewContainer).prepend(itemView.el); } }, 
0
source

Source: https://habr.com/ru/post/914169/


All Articles