MarionetteJS - Nested Views

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.marionette/1.8.6/backbone.marionette.js"></script>
<div id="apartments"></div>

<script type="text/html" id="appartment">
    <div>
        <h2>Apartment: <%=apartment%></h2>
        <ul></ul>
    </div>
</script>
   
<script type="text/html" id="room">
    <h3><%=name%></h3>
    <ul></ul>
</script>

<script type="text/html" id="chair">
    <b><%=chairType%></b>
</script>

CSS

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');

JavaScript

var App = new Marionette.Application();

App.addRegions({
    "apartments": "#apartments"
});

App.on("initialize:after", function() {
	Backbone.history.start();
});

App.module("Fiddle", function(Mod, App, Backbone, Marionette, $, _){
    
    var apartments = [
        {apartment: '1a', rooms: [
            {name: 'master bed', chairs: []},
            {name: 'kitchen', chairs: [
                {chairType: 'stool'}, {chairType: 'stool'}]},
            {name: 'living room', chairs: [
                {chairType: 'sofa'}, {chairType: 'love seat'}]}]
        },
        {apartment: '2a', rooms: [
            {name: 'master bed', chairs: []},
            {name: 'kitchen', chairs: [
                {chairType: 'shaker'}, {chairType: 'shaker'}]},
            {name: 'living room', chairs: [
                {chairType: 'sectional'}]}]
        }];
    
    var chairModel = Backbone.Model.extend({});
    
    var roomModel = Backbone.Model.extend({
        initialize: function(attributes, options) {
            this.chairs = new Array();
            _.each(attributes.chairs, function(chair){
              this.chairs.push(new chairModel(chair));    
            }, this);
        }          
    });
    
    var ApartmentModel = Backbone.Model.extend({
        initialize: function(attributes, options) {
            this.rooms = new Array();
            _.each(attributes.rooms, function(room){
              this.rooms.push(new roomModel(room));    
            }, this);
        }  
    }); 
            
    var ApartmentCollection = Backbone.Collection.extend({
        model: ApartmentModel
    });

    var ChairView = Backbone.Marionette.ItemView.extend({
        template:'#chair'
    });
    
    var RoomView = Backbone.Marionette.CompositeView.extend({
        template: '#room',
        itemViewContainer: 'ul',
        itemView: ChairView,
        initialize: function(){
            var chairs = this.model.get('chairs');
            this.collection = new...