In Part 1 we looked at using Backbone alerts. This time, the navbar!
It would be very simple (and not very useful), to create a Backbone View that renders a static navbar.
But we want a modular, composable app; where each section of the application can add it’s own menu items.
We can start with a template:
<div class="fill"> <div class="container"> <a class="brand" href="#">MyApp</a> <ul class="nav"> <% _.each(links, function(link) { %> <li><a href="<%= link.url %>"><%= link.name %></a></li> <% }); %> </ul> </div> </div>
Obviously our model will consist of a collection of links:
(function($) { var Link = Backbone.Model.extend(); var LinksCollection = Backbone.Collection.extend({ model: Link }); var NavBarView = Backbone.View.extend({ el: $('#navbar'), render: function(eventName) { var self = this; $.get("templates/navbar/navbar.htm", function(data) { $(self.el).html(_.template(data)({ links: self.model.toJSON() })); }); return this; }, addLink: function(link) { this.model.add(link); } }); app.navbar = new NavBarView({ model: new LinksCollection() }); })(jQuery);
Populated by other modules:
(function() { ... app.navbar.addLink({ url: "#something", name: "Something" }); })();