Search code examples
marionette

Listen to sub-sub views in Backbone Marionette


I have a collection view, and each item view is a composite view, which also has a item view. I want to listen to the events from this last (sub-sub) item view.

View.Block = Marionette.Layout.extend({
    triggers: {
        'click .content': 'block:click'
    }
});

View.Category = Marionette.CompositeView.extend({
    itemView: View.Block
});

View.Categories = Marionette.CollectionView.extend({
    itemView: View.Category
});

In my controller I only have a reference to View.Categories:

var categories_view = new View.Categories({
    collection: categories
});

Is it possible to listen to click events from View.Block using Marionette's built-in view events? I tried categories_view.on('itemview:block:click') but that won't work as View.Block isn't an item view of View.Categories, but of View.Category.


Solution

  • You'll need to use a module- or application-level event aggregator to achieve your objective:

    events: {
      "click .something": "triggerEvent"
    },
    
    triggerEvent: function(e){
      myApp.trigger("something:clicked", e);
    }
    

    (myApp is the instance of your Marionette application.)

    Then listen for that event:

    myApp.on("something:clicked", function(e){
      e.preventDefault();
      console.log("something was clicked");
    });