The main layout for using events caused by a child view in one of its regions

Using MarionetteJS v1.0.3.

I have an instance of Marionette.Layout , which has two areas.

The first area is the CompositeView on the left, and the other area is the ItemView on the right.

CompositeView displays several ItemViews.

The idea is that the user clicks on one of the items in the collection on the left to fully display the selected entry in the ItemView on the right.

How the layout at the top subscribes to events in the chain: Layout> Region> Composite element> Item element

Since the layout at the top is the only one who knows about the detailed area on the right, this event needs to be consumed here completely from the CompositeView, where the click event will occur. I know that there are global events, but they are global, and there may be several layouts at the same time, so their events will 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); } } }); 
+4
source share
2 answers

Just use events. When the user clicks on an item, fires an event with MyApp.trigger("item:clicked", myItemInstance) . Then in your layout just listen to the event with

 MyApp.on("item:clicked", function(myItemInstance){ // do stuff }); 

Please note that you can also “automatically” trigger events from the itemView bubble in the collection / composite view (see https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md#itemview -event-bubbling-from-child-views )

Here you can see an example of using events to control your application: https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/apps/contacts/list/list_controller.js

This code is extracted from a book that I write at Marionette: https://leanpub.com/marionette-gentle-introduction (free sample here: <a3> )

+7
source

In short, you can bind to this event after displaying the CompositeView on the Layout with:

 yourLayout.region.currentView.on('item:clicked', yourFunction); 

This is a much better solution than using global events. Global events work for semantic reasoning, saying "this event is globally related to the state of my application" and (in my opinion) actually represent an anti-pattern that is needed only when the project architecture has become a mess and needs refactoring.

The best approach to events is always to trigger an event from the object in which it occurred, and always watch the events on the objects that trigger them.

+10
source

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


All Articles