You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

Bootstrap Alerts with Backbone Views

One of the nice things about Bootstrap is that it provides reusable HTML/CSS components for common tasks such as displaying buttons, tabs, forms, and alerts (among other things). The markup for an alert is very simple:

<div class="alert alert-error">
<a href="#" class="close">&times;</a>
<strong>Oops!</strong> Something went terribly wrong.
</div>

A jQuery plugin that comes with Bootstrap is used for the close button. I found myself duplicating this markup in a Backbone.js project with various Underscore templates scattered around the view classes, so for the sake of DRYness, I decided to whip up a simple view to encapsulate the markup and behavior. Here’s the result:

var AlertView = Backbone.View.extend({
	className: 'alert fade in',
	alerts: ['success', 'error', 'info'],
	template: _.template([
		'<a href="#" class="close">&times;</a>',
		'<%= message %>'
	].join('')),
	initialize: function(options) {
		var message = options.msg || '';
		var alert = options.hasOwnProperty('alert') ? options.alert : 'info';

		if(_.indexOf(this.alerts, alert) === -1) {
			throw new Error('Invalid alert: [' + alert + '] Must be one of: ' + this.alerts.join(', '));
		}

		this.alert = alert;
		this.message = message;
	},
	render: function() {
		var output = this.template({ message: this.message });
		this.$el.addClass('alert-'+this.alert).
			html(output).
			alert(); // jquery plugin
		return this;
	}
});

AlertView.msg = function($el, options) {
	var alert = new AlertView(options);
	$el.html(alert.render().el);
	return alert;
};

Now I can use it from my other views for simple alert messages like this:

AlertView.msg(this.$el, { 
     alert: 'error', 
     msg: 'Something went terribly wrong.' 
});

Of course, it can still be improved with shortcut methods and general cleanup, but the goal is not to make it work for every possible alert, just the most common ones.

Leave a comment