Using Bootstrap alerts with Backbone

Developing single page web apps with Backbone.js is an interesting experience. Each individual part of the UI is considered to be a View.

So, for example, if you wanted to display one of Twitter Bootstrap’s alerts you might create a template:

<div id="alert" class="alert-message error fade in">
  <a class="close" href="#">x</a>
  <p><strong><%= title %></strong> <%= message %></p>
</div>

And a module to display it:

MyApp.Errors = {};
 
(function(ns, $) {
  var Error = Backbone.Model.extend();
 
  var errorAlertTemplate = $.get("templates/errors/error-alert.htm", function(data) {
    errorAlertTemplate = _.template(data);
  });

  var renderTemplate = function(self, url, render) {
    if (!self.template) {
      $.get(url, function(data) {
        self.template = _.template(data);
        render();
      });
    } else {
      render();
    }
  };
 
  var ErrorAlertView = Backbone.View.extend({
    el: $('#alert'),
    render: function(eventName) {
      var self = this;
      renderTemplate(self, "templates/errors/error-alert.htm", function() {
        $(self.el).html(self.template(self.model.toJSON()));
      });
      return this;
    }
  });
 
  ns.errorAlert = function(title, message) {
    var error = new Error({ title: title, message: message });
    app.error = new ErrorAlertView({ model: error });
    app.error.render();
    $(".alert-message").alert();
  };
})(MyApp.Errors, jQuery);

You can then use this in your routes:

MyApp.MyModule = {};
 
(function(ns, $, errors) {
  ns.someRoute = function() {
    var somethings = new SomethingCollection();
    somethings.fetch({
      success: function() {
        var view = new SomethingListView({model: somethings});
        view.render();
      },
      error: function() {
        errors.errorAlert("ERROR:", "Failed to retrieve somethings");
      }
    });
  };
})(MyApp.MyModule, jQuery, MyApp.Errors);

3 thoughts on “Using Bootstrap alerts with Backbone

  1. Mirko February 11, 2012 / 11:07 pm

    Great example! Thanks!

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