Marionette bubble event from itemview to parent layoutview?

Jon picture Jon · Jun 1, 2013 · Viewed 19.1k times · Source

I have a layout view with a region, in that region I have a item view that triggers an event but it doesn't seem to be bubbled up to the layout view. Am I doing something wrong or is this designed behavior? I assume the itemview prefix is not added as the parent view is not a collection view? Either way the event is never bubbled to the layout view.

layoutView = Marionette.Layout.extend({
        template: "#layout-template",
        regions: {
            titleRegion: "#job-title-region"
        },
        triggers: {
            "save:clicked" : "onSaveClicked"
        },
        onSaveClicked: function (args) {
            alert('Clicked');
        }
    });

childview = Marionette.ItemView.extend({
        template: "#child-template",
        triggers: {
            "click .js-save": "save:clicked"
        }
    });

UPDATE:

See this fiddle http://jsfiddle.net/7ATMz/11/ I managed to get the layout view to listen to the child event but I have to wire it up outside of the layout view itself and break encapsulation. Can I do this in the layout view in anyway?

Thanks,

Jon

Answer

David Sulc picture David Sulc · Jun 1, 2013

Triggers don't quite work like that: your layout is using them wrong. Triggers are a convenience to raise an event signal given a certain interaction (e.g. a click).

What you want is to use triggerMethod (https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.functions.md#marionettetriggermethod) to trigger a function in your layout. See http://jsfiddle.net/ZxEa5/ Basically, you want this in your show function:

childView.on("btn:clicked", function(){
  layout.triggerMethod("childView:btn:clicked"); 
});

And in your layout:

onChildViewBtnClicked: function(){
   https://leanpub.com/marionette-gentle-introduction
});

Event bubbling only happens automagically with collection?composite views because they're tightly associated with their item views. If you want a layout to monitor one of its child views, you need to set that up on your own.

Shameless plug: if you want to learn more about how to structure and clean up your code with Marionette, you can check out my book (https://leanpub.com/marionette-gentle-introduction) where this type of concept (and its applications) is explained in more detail.