Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.Marionette Layout to consume the events triggered from a child view in one of it's regions

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);
        }
    }
});
like image 489
simbolo Avatar asked Dec 02 '22 23:12

simbolo


1 Answers

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.

like image 115
monokrome Avatar answered Feb 14 '23 21:02

monokrome