Rendering Layouts and sub-views in Marionette / Backbone.js
Asked Answered
D

1

2

I have a working solution in regard to rendering layouts with views in regions in a Marionette application I'm working on, but something doesn't feel right about it. Do you have to append anything directly to the DOM?

Here is my method in the controller:

 //Grab the main Layout
        var layout = new APP.Views.LayoutView();

        //Render that layout
        layout.render();

         //Make the model
        var simpleModel = new APP.Models.simpleModel({
          "field1" : "foo",
          "field2" : "bar"
        });


        layout.header.show(new APP.Views.subView({model: simpleModel}));

        $('body').html(layout.el);

It's the last part that feels unnatural to me. This is primarily because if I move 'layout.header.show' to after the .html(), then it doesn't render properly. What's the point of regions if they aren't dynamically changable after pushing it to the DOM?

Here is my layout:

APP.Views.LayoutView = Backbone.Marionette.Layout.extend({

  template: "#layoutTemplate",

  className : 'wrapper',

  regions: {
    header: "#header",
    footer: "#footer"
  }


});

and here is the sub view:

APP.Views.subView = Backbone.Marionette.ItemView.extend({

    template : '#headerTemplate',

    className: 'container'


});

As I said, this works, but it feels like I'm not using regions properly. Is there a better, more concise way to do this that will allow you access to regions after you rend the layout to the DOM?

In the Marionette documentation there seems to be no mention of using .html() to get things on the page -- I'm wondering if this is left out because it's not needed or that it's assumed.

Can anyone help?

Desmarais answered 27/3, 2013 at 12:7 Comment(0)
D
4

Okay, so it seems like this can be circumvented by creating a 'region' in your application, then using .show() to show the layouts inside of it.

Here is a link to a fiddle I found on SO that helped: http://jsfiddle.net/TDqkj/6/

as well as to another question: Understanding layouts in Marionette for Backbone.js

The fiddle in particular has this code:

App = new Backbone.Marionette.Application();
App.addRegions({
   'nav': '#nav',
  'content': '#content'
});

Which the programmer than uses to add layouts to those regions -- meaning you never have to append to the DOM.

If anyone else has a more elegant solution, please post!

Desmarais answered 27/3, 2013 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.