The basic situation is this:
I have a Composite View and an Item View. I construct the Composite view passing it a model and a collection. The model data is used to populate the template for the Composite view. The collection data is used to populate the Item View for the Composite View.
What I want to do is this: in a template helper for the Item view I want to access the model data for the Composite View. I've got as far as accessing the view instance of the Item View. I thought that might give me a handle on the Composite View, from where I could get to its model, but it doesn't.
Is there a way I can do this - access the composite view instance from one of its item view instances?
Thanks
--Justin Wyllie
If you want to access data from the parent
CompositeView
you can do a number of different things.Either pass that data directly to the
ItemView
through theitemViewOptions
helper function on theCompositeView
. Note: This option has changed tochildViewOptions
in Marionette 2.Invoke a method directly on all of the children view from the
CompositeView
and pass whatever you want into that method.Trigger an event on or listened for by the
ItemView
.None of these options are directly accessing the parent view from the child but should do what you want. Below is code for how to use each of these approaches to pass the
CompositeView
's model to the children view.I didn't answer the question. But changing the approach works. Instead of trying to access the 'parent' Composite View from the Item View I access the Item View from the Composite View:
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md#onbeforeitemadded-callback
I can modify the model of the current item view (based on a value in the model of the Composite View).
Thought I'd share how Andrew Hubbs suggestion helped me. I was trying to display a parent model property inline with my item template. I used Marionette's templateHelpers property to do this in combination with one of Andrew's suggestions.
I tried to keep the example brief:
Example Composite template - myView Template:
Example item template - myItemTemplate:
Views:
An example of how this would be implemented: