Using Bootstrap with Backbone (Part 2)

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 %>"><%= %></a></li>
      <% }); %>

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) {

  app.navbar = new NavBarView({ model: new LinksCollection() });

Populated by other modules:

(function() {
  app.navbar.addLink({ url: "#something", name: "Something" });

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s