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 %>"><%= 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" });
})();
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s