Which component to use to implement a menu?

Question!

I want to display a menu like:

Obi Wan Kenobi
  My friends
  Options

My lightsabers
  Blue lightsaber
  Green lightsaber 
  Add a lightsaber

As you can see, the My lightsabers menu is a list of items, but the link to add a new lightsaber is independent.

I believe I should use a CollectionView to render the lightsabers list, but how to render the "add" link?

Do you have any example of such menus?

The question can be generalized in: How to customize bits of HTML rendered by Marionette without breaking thing it does?



Answers
I'd use a CompositeView for this, because of the need for the add link.

You would set up a template that contains a placeholder for the actual list, and then has the add link and all the necessary other bits as well. Then modify the appendHtml method of the composite view to place the actual items in the correct spot.

For example, here's a template that would get you down the path:

<script id="light-saber-menu-template" type="text/html">
  <h4>My Lightsabers</h4>
  <ul id="light-sabers">
    <li class="divider"></li>
    <li><a href="#">Add A Lightsaber</a></li>
  <ul>
</script>

<script id="light-saber-menu-item-view" type="text/html">
  <%= name %>
</script>

In this example, I would use the divider ul as the location to put the items, inserting them before the divider:


MenuItem = Backbone.Marionette.ItemView.extend({
  template: "#light-saber-menu-item-template",
  tagName: "li"
});

MenuView = Backbone.Marionette.CompositeView.extend({
  template: "#light-saber-menu-template",

  itemView: MenuItem,

  appendHtml: function(cv, iv){
    var $divider = cv.$(".divider");
    $divider.before(iv.el);
  }
});

myLightSabers = new LightSaberCollection(... data ...);

menu = new MenuView({
  collection: myLightSabers
});

menu.render();

This should produce a <ul> with the items you expect:

<div>
  <h4>My Lightsabers</h4>
  <ul>
    <li>Blue</li>
    <li>Green</li>
    <li>Red</li>
    <li class="divider"></li>
    <li><a href="#">Add A Lightsaber</a></li>
  </ul>
<div>

For more examples on using a CompositeView, see this blog post: http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/



This video can help you solving your question :)
By: admin