Jun 09 2014

Nested Views in Backbone.Marionette

A couple of weeks ago we published an article about Functional Programming that used a bagel as an example. It was very well-received, so why not try again? This week @samccone is back with the delicious carbohydrate to talk about Nesting Views in Marionette.js.

Nesting views can be a difficult task at first glance. Marionette makes your life easy with an elegant view layer that simplifies complexity and hides the implementation details. This allows you to focus on getting things done instead of reinventing the wheel.


Suppose that we are tasked with creating an interface that covered the process of making a bagel sandwich. As part of the job, you have to render a DOM tree representing the bagel on the screen according to a set of ingredients.

Making a sandwich is pretty darn complex though. You have to add the right ingredients in the right order inside of a bagel wrapped in some foil based on some data structure.

Let's assume that the output we need to generate looks looks like this.

<foil>
<bagel>
<bacon></bacon>
<tomato></tomato>
<hummus></hummus>
<sprouts></sprouts>
<avocado></avocado>
</bagel>
</foil>

It might look like this (click through to see code example): https://jsfiddle.net/thejameskyle/RqQ2x/

Programmatically rendering this bagel according to our data seems like it will be a pain. However, Marionette.js provides us with simple constructs to accomplish our goals.

The three pieces we will use are

  • A Region
  • A View
  • A CollectionView

Let start out with a foil

Region
that will hold our bagel.

var foil = new Marionette.Region({
el: "foil",
});

Now we will create our

CollectionView
class that will hold the contents of the bagel, and a
View
class to output each Ingredient.

var BagelItem = Marionette.View.extend({
tagName: function () {
return this.model.get("name");
},
});
var Bagel = Marionette.CollectionView.extend({
tagName: "bagel",
itemView: BagelItem,
});

Alright, so far, so good. Now let's put this all together.

var ingredients = new Backbone.Collection([
{ name: "bacon" },
{ name: "tomato" },
{ name: "hummus" },
{ name: "sprouts" },
{ name: "avocado" },
]);
foil.show(new Bagel({ collection: ingredients }));

And just like that we have rendered a delicious bagel onto the screen.

Take a look at the finished product here.

Hopefully this gives you a taste of how simple it is to take a seemingly abstract and complex task and break it into small composable chunks with Marionette.js.

Like to write code? Love bagels? We're hiring!

MojoTech

Share: