Dynamically add regions to Marionette layout

11,268

Marionette v1.0 (v1.0.2 is latest, right now) supports dynamic regions in Layouts.


var MyLayout = Marionette.Layout.extend({
  template: "#some-template"
});

var layout = new MyLayout();
layout.render();

layout.addRegion("someRegion", "#some-element");

layout.someRegion.show(new MyView());
Share:
11,268
Thalis K.
Author by

Thalis K.

Updated on July 24, 2022

Comments

  • Thalis K.
    Thalis K. almost 2 years

    I have a layout, but cannot define all of its regions in advance because they are not known.

    So later on an ItemView is created and I'd like to create a new region in the layout using the view's ID as the region's name so I can then say:

    layout.dynamicRegionName.show(newItemView);
    

    But there is cyclic dependency here.

    1. I haven't rendered the view yet, so I cannot make a reference to its DOM element to be used in the layout's call to .addRegion()

    2. I cannot render it, precisely because I want it to get attached to the DOM tree through the dynamically added region by calling its .show()

    @DerickBailey In the Marionette.Layout docs in github I believe there is an error in the example that has: layout.show(new MenuView());

    but technically this is close to what we'd need here i.e. to be able to do:

    layout.addRegion(VAR_WITH_NEW_REGION_NAME, aViewInstance);
    

    and have this add a new Region into the layout rendering inside it directly the view instance.

    Am I missing some other obvious way to achieve this? Is that a known missing functionality? Is there a reason not to have it?

    I'm aware of this previous Q: "Dynamically add/remove regions to a layout" but don't see any clear/definite answer to it.

  • Lorenzo B
    Lorenzo B over 10 years
    Helpful answer. My question is the following. Does the element (#some-element) need to be within the template or not? In other words, does the template contains that element or the addRegion method appends it for me? See my question for this stackoverflow.com/questions/20570284/…
  • yves amsellem
    yves amsellem about 10 years
    Yes, the template has to contain the el. So addRegion is kind of weird :-/
  • backdesk
    backdesk almost 10 years
    Not really 'weird' as such. A region is a container that just wraps around a given element. Likewise when you remove a region it won't remove the DOM element, just the region object.
  • Vlad
    Vlad over 8 years
    @backdesk I understand it's meant to work that way but just because it's an intended feature by the author doesn't mean it's not weird from an end-user point of view. It does feel weird that I still need to have a wrapper el in order to "add Region". I came to this question after googling "dynamic marionette region" hoping I would be able to have a single empty root element to which various regions could be attached. That's what people think normally when they hear "dynamic". To me it sounds pretty static.