New in using Backbone.js and underscore.js, trying to create a list of submenus (second level) for my menulist (first level).
So this is my menulist I created in JSON (which I have confirmed exists by printing it to the browser console):
[
{
"name": "Sök kund",
"path":
[
{
"subName": "Fondkonto",
"subPath": "#fondkonto"
},
{
"subName": "Kassakonto",
"subPath": "#kassakonto"
},
{
"subName": "Nytt sparande",
"subPath": "#nyttsparande"
}
]
},
{
"name": "Ny kund",
"path": "#new_customer"
},
{
"name": "Dokument",
"path": "#documents"
},
{
"name": "Blanketter",
"path": "#forms"
}
]
And this is the code I put out to show in my index-file, which for now prints only the first-level:
<script type="text/template" id="menus">
{{ _.each(menus, function(menu) { }}
<li><a href="{{= menu.path }}">{{= menu.name }}</a>
<ul>
<li>
<a href="{{= menu.path.subPath }}">{{= menu.path.subName }}</a>
</li>
</ul>
</li>
{{ }); }}
</script>
And in case you want to know how the view and model/collection are built:
var Menus = require("../collections/menus");
var AllMenus = Backbone.View.extend({
el: "#menuContent",
template: _.template(document.getElementById("menus").innerHTML),
initialize: function() {
"use strict";
this.menus = new Menus();
this.listenTo(this.menus, "reset", this.render);
this.menus.fetch({
reset: true,
url: "./data/menus.json",
success: function() {
console.log("Succesfully loaded menus.json file.");
},
error: function() {
console.log("There was some error trying to load and process menus.json file.");
}
});
},
render: function() {
console.log( this.menus.toJSON());
this.$el.html(this.template({ menus: this.menus.toJSON() }));
return this;
}
});
var viewMenus = new AllMenus();
Model:
var Menu = Backbone.Model.extend({
defaults: {
name: "",
path: ""
}
});
module.exports = Menu;
Collection:
var Menu = require("../models/menu");
var Menus = Backbone.Collection.extend({
model: Menu
});
module.exports = Menus;
Don't mean to paste so much code, but necessary to make this so you understand how I built it up. But I got stuck by trying to show my subMenus with no success to it.