Using MarionetteJS v1.0.3.
I have a instance of a Marionette.Layout
which has two regions.
The first region is a CompositeView
on the left, the other region is a ItemView
on the right.
The CompositeView renders multiple ItemViews.
The idea is, the user clicks on one of the items in the collection on the left, to display the selected record in full on the ItemView on the right.
How can the Layout at the top subscribe to the events in the chain: Layout > Region > CompositeView > ItemView
As the Layout at the top is the only one aware of the detailed region to the right, the event needs to be consumed here all the way from the CompositeView where the click event would be triggered. I know there are global events, but they are global, and there might be multiple Layouts running at once so their events would collide.
LeftListPanelView = Marionette.CompositeView.extend({
template: "#leftPanel",
itemViewContainer: "ul",
events: {
"click li": "rowClicked"
},
rowClicked: function (e) {
var itemid = $(e.currentTarget).data("itemid") * 1;
var selectedItem = this.collection.get(itemid);
if (selectedItem) {
this.trigger("itemSelected", selectedItem);
}
}
});
In short, you can bind to that event after showing your CompositeView
on your Layout
with:
yourLayout.region.currentView.on('item:clicked', yourFunction);
This is a much better solution than using global events. Global events work for the semantic reasoning of saying "this is event that is globally related to the state of my application" and (in my opinion) actually represent an anti-pattern that only needs used when project architecture has become a mess and needs refactoring.
The best approach with events is always to trigger an event from the object that it occured within, and to always watch events on the objects triggering them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With