Search code examples
javascriptjquerybackbone.jsmarionette

Backbone Marionette Composite View Rendering Template


I'm trying to render a list with a Marionette CompositeView. I am not sure why the rendered list just has an item displaying the word result. I was expecting the first item to display Level 1.

Here is a fiddle to my current code: http://jsfiddle.net/16L1hen4/

Here is my JS, template, and data:

JavaScript:

var App = new Backbone.Marionette.Application();

App.addRegions({
    mainRegion: '#main' 
});

var TreeModel = Backbone.Model.extend({    
});

var TreeCollection = Backbone.Collection.extend({
    model: TreeModel,

    url: 'https://api.mongolab.com/api/1/databases/backbone-tree/collections/tree?apiKey=somekey'

});

var TreeView = Backbone.Marionette.CompositeView.extend({

    initialize: function() { 
        console.log(this.collection); 

    },

    tagName: 'ul',

    template: _.template( $('#tree-template').html() )
});

var treeCollection = new TreeCollection();
treeCollection.fetch().done(function () {
    var treeView = new TreeView({collection: treeCollection});
    App.mainRegion.show(treeView);    
});

Template:

<div id="main"></div>

<script type="text/template" id="tree-template">
    <li><%- name %></li>
</script>

JSON Data:

{
    "_id": {
        "$oid": "54adab80e4b0aa674b256836"
    },
    "name": "Level 1",
    "children": [
        {
            "name": "Child 1 - Level 2",
            "children": [
                {
                    "name": "Jon - Level 3"
                },
                {
                    "name": "Mary - Level 3"
                }
            ]
        },
        {
            "name": "Child 2 - Level 2",
            "children": [
                {
                    "name": "Bill - Level 3"
                }
            ]
        }
    ]
}

Solution

  • You are using a CompositeView to display a Collection, but you need to define a childView to render the models

    var LeafView = Backbone.Marionette.ItemView.extend({
        // ...
    });
    
    var TreeView = Backbone.Marionette.CollectionView.extend({
        childView: LeafView
    })
    

    here is an updated fiddle. http://jsfiddle.net/6ok1rptq/

    Now the "result" showing in the html, without being familiar with the underscore source, I believe this is caused by the fact that the data given to the template is null, and a quick look at the source of underscore shows that it is using with

    http://underscorejs.org/docs/underscore.html#section-148

    "If a variable is not specified, place data values in local scope."

    Meaning that the template can't find a "name" variable, and will instead look it up in the global scope (window)

    Result is just the name of the jsfiddle iframe containing the result of the fiddle

    <iframe name="result" ...>