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 popu
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 the itemViewOptions
helper function on the CompositeView
. Note: This option has changed to childViewOptions
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.
// Pass model into ItemView on init
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function (options) {
this.parentsModel = options.parentsModel;
}
});
var MyCompView = Backbone.Marionette.CompositeView.extend({
itemViewOptions : function () { return { parentsModel: this.model }; }
itemView : MyItemView
});
// Invoke function on ItemView, passing data in
var MyItemView = Backbone.Marionette.ItemView.extend({
doSomethingWithParent : function (parentModel) {
// do cool thing with parentModel
}
});
var MyCompView = Backbone.Marionette.CompositeView.extend({
itemView : MyItemView,
onRender : function () {
this.children.call("doSomethingWithParent", this.model);
}
});
// Trigger event that ItemView knows about
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function () {
this.listenTo(this, "special:event", function (parentModel) {
// Do cool things
});
}
});
var MyCompView = Backbone.Marionette.CompositeView.extend({
itemView : MyItemView,
onRender : function () {
this.children.each(_.bind(function (childView) {
childView.trigger("special:event", this.model);
}, this));
}
});