0

I have a nested composite view that checks its model for a collection, and if so sets that collection to itself as its collection.

onRender: ->
  if model.attributes.has_collection
    @collection = model.get 'myCollection'

This works quite well when the model has a collection, and the item view(s) all display, and when I add a new model to the collection, a new view appears.

However when there is no collection, and the button is clicked to create a new model, I need to create the model, set the collection (a collection of one) to the view's model, and get the view to display the model and any further models that are added. I have tried various things, right now I set the collection on the model and then run this function :

class List.myCompositeView
  childView: myView
  // *** //
  setChildren: ->
    @collection = @model.get 'myCollection'
    @render()

The first model appears as it should, but further models that are created do not display. To repeat, they do appear when the collection is set in the onRender function. I realize there is lots of code that I did not add here, so if there is something (potentially) relevant to the problem that you need to know, let me know. Could it be that the view is not binding to the collection's events properly? Thanks!

jacob.mccrumb
  • 681
  • 5
  • 18

1 Answers1

0

A marionette collectionView has a private method called _initialEvents. When your collectionView is constructed it sets up this method to be called the first time the view is rendered. If your first render is when a collection view is not set then this would make sense that the events would not get wired up correctly. You should be able to call this private method after you set the collection and everything should work: @_initialEvents()

If it is helpful, this is the implementation of that method:

if (@collection) {
  @listenTo(this.collection, 'add', @_onCollectionAdd);
  @listenTo(this.collection, 'remove', @_onCollectionRemove);
  @listenTo(this.collection, 'reset', @render);

  if (@getOption('sort')) {
    @listenTo(@collection, 'sort', @_sortViews);
  }
}
dchapman
  • 365
  • 5
  • 20
  • Thank you for the response! Just got around to trying this and things are closer but not quite on. I set the collection and log out the view to inspect it: collection length is 1, childview length is 0. Each time I click the add button, the length of each increases by 1 (so I see all the new children). Basically, a new childview is not created for the first. – jacob.mccrumb Nov 23 '15 at 20:57
  • Now I set the collection, render the composite view, and then call @_initialEvents() which keeps everything else going. I fear I might be over-complicating it, and not sure if the @render() has any negative side-effects that I should be avoiding, but it works which is a good place to be :) Thanks again! – jacob.mccrumb Nov 23 '15 at 21:00