twsmith
twsmith

Reputation: 401

Backbone Marionette LayoutView can't find DOM element

I'm having trouble rendering a Marionette LayoutView and showing a region inside that layout.

My layout file:

template: '#fooTemplate',
    regions: {
        barRegion: '.bar'
    }

My HTML:

<script id="fooTemplate" type="text/template">
    <div id="fooDiv">
        <div class="bar">
        </div>
    </div>          
</script>

The code that renders the layout and shows the region:

var FooLayout = require('./browserify/path');
var fooLayout = new FooLayout({el:"#fooDiv"})

collectionView = new CollectionView({
    collection: collection
});
fooLayout.render();
fooLayout.barRegion.show(collectionView);

I get an error Uncaught Error: An "el" #foo .bar must exist in DOM

What am I missing in LayoutView's functionality? I have a similar example working just fine, but for some reason I cannot replicate it.

Upvotes: 4

Views: 6288

Answers (1)

knpsck
knpsck

Reputation: 833

It happens because view is detached from DOM. If you specify {el:"#fooDiv"}, #fooDiv element must be in DOM. I think there should be something like this:

<script id="fooTemplate" type="text/template">
    <div class="bar"></div>      
</script>

Add #fooDiv in html markup

<body>
    ...
    <div id="fooDiv"></div>
    ...
</body>

and then you can do

// "wrap" new Layout around existing div
new FooLayout({ el: '#fooDiv' });
// etc.

or

// create a new DOM element with the id 'fooDiv':
var fooLayout = new FooLayout({ id: 'fooDiv' });
fooLayout.render();
document.body.appendChild(fooLayout.el); // or $('body').append(fooLayout.el);

Upvotes: 4

Related Questions