8
votes

We are currently building a Marionette based application. Basically, we have a Marionette Application that has multiple regions defined on it. Each region will act as a container for different Modules to display their views. I want each Module to have full control of what is being displayed in it's container, but I want the Application to allocate these regions. For simplicity, let's say that each module just has a simple ItemView.

I'm considering 2 approaches to populating those regions with the module views.

The first approach says that when each module is initialized, it will create its view and it will call the application to display its view in the specified region, for example:

var app = new Marionette.Application();
app.addRegions({
    regionA: "#regionA",
    regionB: "#regionB"
});

app.module("moduleA", function(moduleA, app, ...){
    moduleA.on("start", function(){
        var viewA = new MyViewA();
        app.regionA.show(viewA);
    }
});

app.module("moduleB", function(moduleB, app, ...){
    moduleB.on("start", function(){
        var viewB = new MyViewB();
        app.regionB.show(viewB);
    }
});

The second approach says that each module should expose some function that returns its view. The Application will call that function when ready and it will stick the view in the designated region.

I'm not sure which approach is better and would be happy to hear opinions.

2

2 Answers

7
votes

I would definitely go with the second approach, after having gone with the first approach in the past I am now hitting the limitations of this approach and moving to the second approach. I wrote a blog post about it here

0
votes

It depends which approach you take, both are fine, we choose the second option because we use require.js to load our modules dynamically.

    var dashboardPage = Backbone.Marionette.Layout.extend({

      template: Handlebars.compile(tmpl),

      regions: {
        graphWidget     : "#graphWidget",
        datePickerWidget: "#datePickerWidget",
        searchWidget    : "#searchWidget"
      },

      widget: {
          graphWidget: null,
          datePickerWidget: null,
          searchWidget: null,
      },

 initialize: function(options){

        this.someId= options.someId;

        //if have someId ID - fetch model;        
        if(this.someId){
            //fetch model if campaignId not null
            this.modelAjax = this.model.fetch();
         }

      onShow: function() {
          var that = this;

          if(this.modelAjax){
            this.modelAjax.done(function(){

                that.widget.graphWidget= new graphWidget(graphWidgetOptions);
                that.listenTo(that.widget.graphWidget, 'graphWidget', that.getGraphWidgetData, that);
                ....
                that.graphWidget.show(that.widget.graphWidget);
                that.datePickerWidget.show(that.widget.datePickerWidget);