0
votes

I have a header region where i like to have my navigation available in the initial markup (because of SEO)

    <header id="header-region">
        <ul id="menu">
            <li>frontpage</li>
            <li>about</li>
            <li>contact</li>
            <li>testing</li>
        </ul>
    </header>

Then i created a Marionette Layout View:

var MenuView = Backbone.Marionette.ItemView.extend({});
var menuView = new MenuView({
    el: '#menu'
}); 

App.headerRegion.attachView(menuView);

This works flawless, but when i later change the headerRegion content

App.headerRegion.show(anotherView);

And then wanna switch back to the original mainView using

App.headerRegion.show(menuView);

It tries to render the menuView but because it has no "template" it fails, can i somehow reuse the same view instance without re-render it ? Or is the "Marionette way" of doing it to re-initialize a new menuView ? (im just curious if i have a rather complex view that needs to be swapped out quite alot, the view re-render each time could be quite expensive)

2

2 Answers

1
votes

When a region's content is swapped in Marionette the previous view that was displayed in that region will be closed; and you generally want to avoid reusing views that have previously been closed. There is quite a bit of binding (of event and dom component) that goes into inflating a view and you could cause hard to track bugs re-using views because some of those bindings might not happen.

I've ran into a few my self like Switching views on regions loses the event bindings.

0
votes

Calling App.headerRegion.show(anotherView); will dump the contents of your header region and replace those with the contents of anotherView. When you try to revert the region to its previous state by calling App.headerRegion.show(menuView), the markup you were relying on no longer exists.

The Backbone/Marionette way to do this is to use a template. Marionette uses underscore templating by default, so you can just include the following on your page:

<script type="text/template" id="menu">
    <ul>
        <li>frontpage</li>
        <li>about</li>
        <li>contact</li>
        <li>testing</li>
    </ul>
</script>

And then define your MenuView as:

var menuView = new MenuView({
    template: '#menu'
});