Ksthawma
Ksthawma

Reputation: 1285

LayoutView that shows any number of views

If I have a LayoutView which has two regions defined,
myLayout.getRegion('regionA').show(myView1)
myLayout.getRegion('regionB').show(myView2)
This is fine.

myView3 cannot be appended because myLayout does not have a third region, and the template has no more placeholder either.

If I want to have a LayoutView (or whatever container) which accepts an array/ordered collection of any number of views and show them simply as one after another, what should I do?

(I think the answer is not CollectionView as it expects one childView and a Collection of Models.)

Upvotes: 0

Views: 81

Answers (3)

Ksthawma
Ksthawma

Reputation: 1285

After spending days trying to write a LayoutView that accepts an arbitrary number of views, I have made it, but then found Backbone Babysitter which is tidy.

new Backbone.ChildViewContainer();    

Upvotes: 0

mavarazy
mavarazy

Reputation: 7735

From official documentation: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.layoutview.md

  1. Marionette region, can be a defined as a function

Regions can be specified on a LayoutView using a function that returns an object with the region definitions. The returned object follow the same rules for defining a region, as outlined above.

 Marionette.LayoutView.extend({   // ...

   regions: function(options){
     return {
       fooRegion: "#foo-element"
     };   },

   // ... });
  1. You can addRegion to the LayoutView

Regions can be added and removed as needed, in a LayoutView instance. Use the following methods:

addRegion
addRegions
removeRegion

So you can just addRegion to Layout, before showing new element

Try this:

            layout.addRegion("region1", "#region1");
            layout.$el.append("<div id='region1'/>");
            layout.region1.show(panelView);

It worked for me

Upvotes: 0

Alex Ponomarev
Alex Ponomarev

Reputation: 945

If you have models attached to the views, the answer is CollectionView, it has a nice getChildView method that is used to find proper view class based on the properties of the item model, see CollectionView docs

If you don't care about the models then idea of MultiRegion class will work for you — it allows multiple views to be attached to single Region. It is quite outdated now though, feel free to send a pull request if you will update it to latest Marionette version

Upvotes: 1

Related Questions