Backstrap

Backstrap

Are you looking for something meaty to connect
the MVC backbone and the UI skin
of your client-side JavaScript app?
Look no further, you've found it:
Backstrap!

The Backstrap JavaScript library provides a layer of functionality
tying together Bootstrap and Backbone.
It makes it easy to lay out a clean, well-designed user interface
with interface components that are tightly bound to data model objects
backed by a powerful model-view-control application framework.
If you're wondering why that's such a great idea,
take a look at this popular article by Christophe Coenraets:
Sample Application with Backbone.js and Twitter Bootstrap.

Backstrap is available on GitHub
and as a Composer component on Packagist.
The project depends on Backbone, Bootstrap, jQuery and Underscore.
Unless you've built your own Bootstrap theme, you'll also want to
use the bootstrap-default theme.
With Composer, just add

"backstrap/backstrap": ">0.1",
"components/bootstrap-theme": "~3.0"

to your composer.json "require" to get started.

The core Backstrap object is based heavily on
Joe Stelmach's nifty laconic.js package,
which simplifies the generation of DOM content,
and on Backbone-UI which provides a set of
higher-level data-bound components.

To all of that we've added generators for
Bootstrap-enhanced DOM objects and data-bound components,
easy support for Bootstrap's sizing and context-coloring features;
and methods for making complex Bootstrap components like
grids, navbars, button-groups, forms.

Detailed usage

HTML Tags

Backstrap adds a method to the $$ namespace for each known
HTML Element.
These methods should be invoked with a variable-length list of child elements, strings, numbers, or arrays containing these types.
An optional attributes object may be passed as the first argument.
For example:

$$.div({className: 'example'},
$$.p('content')
);

produces

<div class="example">
<p>content</p>
</div>

Various HTML tags get extra Bootstrap decoration by default,
for instance $$.button() automatically adds the Bootstrap "btn" class to your button.
Note that this is the only supported way to build buttons -
you should avoid using, for example, $$.a({className: "btn"}).

Most attributes get applied directly to the created object as HTML attributes;
there are a few special attributes which undergo further processing.
For instance, if you pass a "size" or "context" attribute
it will be converted into a suitable Bootstrap classname.
See Bootstrap Attributes below for more details.

Backstrap, like laconic, adds an appendTo() convenience method
to each DOM object it creates.
See the laconic doc
for a description of laconic.

Some additional methods which build more complex, Bootstrap-enabled tag sets have also been included,
for instance $$.grid(). These are described in the next section, Bootstrap Tags.

In some cases, there is a Bootstrap component name that is the same as an HTML tag name.
To work around this conflict, we make all the plain HTML tag methods accessible in the
$$.plain namespace. Thus for instance in the case of "label", $$.label() will give you
a fully Bootstrapped <label class="label">,
while $$.plain.label() will give you a plain HTML <label>.
Overloaded names include: button, form, input, label, and table. For example:

There are also constructors for building various Backbone.View extensions,
which allow you to make Backbone Model-bound components that are also
Bootstrap-enabled. For instance $$.BasicNavbar() which creates a navbar
whose contents are built from a description provided as a Backbone Collection.
See Components below for more details.

Bootstrap Tags

The Bootstrap-enabled DOM generator methods are:

alert

The $$.alert() method creates a div tag decorated with the Bootstrap "alert" class.

badge

The $$.badge() method creates a span tag decorated with the Bootstrap "badge" class.

breadcrumb

The $$.breadcrumb() method creates an ol tag decorated with the Bootstrap "breadcrumb" class.

button

The $$.button() method creates a button tag decorated with the Bootstrap "btn" class,
and optionally with "btn-*" classes for sizing and context.

$$.plain.button() gives you a bare button tag.

buttonGroup

The $$.buttonGroup() method creates a div tag decorated with the Bootstrap "btn-group" class.

buttonToolbar

The $$.buttonToolbar() method creates a div tag decorated with the Bootstrap "btn-toolbar" class
and also the attribute 'role="toolbar"'.

caret

The $$.caret() method creates a span tag decorated with
the Bootstrap "caret" class, for use as a dropdown menu symbol.

container

The $$.container() method creates a div tag decorated with the Bootstrap "container" class,
and optionally with the "container-fluid" class for fluid layout.

css

The $$.css(url) method is a shortcut for creating CSS stylesheet links.
It creates an HTML <link rel="stylesheet" type="text/css" href="url"> tag.
Use it to load CSS from within your JS code.
For example:

$('head').append($$.css('/css/myStyles.css'));

dropdown

The $$.dropdown() method creates either a button or li tag which contains
a tag set that implements the Bootstrap dropdown component.
The special attribute "labelContent" is used as the dropdown's label (with a dropdown caret automatically added.)
The attribute "type" may be one of "plain (default), "button", or "split-button".
The "align" attribute may be to used to set the text alignment to "right" or "left",
and the "dropup" attribute, if true, makes the menu appear above the button instead of below it.

dropdownGroup

The $$.dropdownGroup() method creates an li tag which contains a ul.
These are decorated with Bootstrap classes to make them function as a group of selections in a $$.dropdown.
The special attribute "labelContent", if provided, produces a section header in the dropdown menu.
It should be populated with content in the form of li tags suitable for menu items.

form

The $$.form() method creates a form tag decorated with the attribute 'role="form"'.

$$.plain.form() gives you a bare form tag.

formGroup

The $$.formGroup() method creates a div tag decorated with the Bootstrap "form-group" class.
Use it to group form inputs with their labels, inside a form.

glyph

The $$.glyph(name) method creates an empty span tag decorated with the Bootstrap "glyphicon" and "glyphicon-{name}" classes.
For example:

$$.glyph('star');

grid

The $$.grid() method creates a nested set of divs. Pass it a "layout" attribute
in the attributes argument to define the grid cells. The "layout" attribute should contain
an array of arrays of cell specifications. Each cell specification can be either
a simple integer specifying the width (in columns) of the cell, or an object
with properties for each device-size for which you want to set a column width.
Use either Bootstrap's short names ("lg", "sm") or full names ("large", "small").
It may also contain a "content" property containing a DOM object to use as
the contents of the cell. For example:

Pass grid a "fluid: true" attribute to get a fluid layout (using Bootstrap's
"container-fluid" class instead of "container" on the top-level div).
See Bootstrap's grid doc for more info on using Bootstrap grids.

We also add a few convenience methods on the top-level div:
appendRows(layout), appendRow(layout), getRow(rowNum), and getCell(rowNum, colNum).
For example:

linkList

The $$.linkList() method creates a div tag decorated with the Bootstrap "list-group" class,
to implement a Bootstrap "linked item list group".
It should be populated with $$.linkListItem()'s.

linkListItem

The $$.linkListItem() method creates an a tag decorated with the Bootstrap "list-group-item" class.
It should be used with $$.linkList().

list

The $$.list() method creates a ul tag decorated with the Bootstrap "list-group" class,
to implement a Bootstrap "list group".
It should be populated with $$.listItem()'s.

listItem

The $$.listItem() method creates an li tag decorated with the Bootstrap "list-group-item" class.
It should be used with $$.list().

media

The $$.media() method creates a div tag decorated with the Bootstrap "media" class.
Passit a DOM object as its "media" attribute, and an optional 'pull: "right"'
if you want it pulled right instead of left.
Its body will be further wrapped in a div with class "media-body".

menuItem

The $$.menuItem(label, href) method creates an a tag
inside an li tag,
decorated with the "menuitem" class and role.
Suitable for use as the content of a $$.dropdown or similar.

nav

The $$.nav() method creates a ul tag decorated with the Bootstrap "nav" class.
Children of $$.nav() should be $$.li()'s.
Remember to mark one of the children with "className: 'active'" to get the proper highlighting.
The nav object has a helper method clearActive() for convenience.
In addition to standard tag attributes,
it accepts several special attributes for configuration of the nav:

type - Required. The type of nav to create - either "tabs" or "pills".
With "type: 'tabs'", you also get "role: 'tablist'" by default.

navbar

The $$.navbar() method creates a nav tag decorated with the Bootstrap "navbar" class
and also the attribute 'role="navigation"' (can be overridden if necessary), to implement a Bootstrap navbar.
Children of $$.navbar() should be either $$.navbarGroup() or $$.navbarForm() objects.
In addition to standard tag attributes,
it accepts several special attributes for configuration of the navbar:

brandContent - Branding visual for left end of navbar (a DOM object or string, default: '').

sr_toggle_text - For screen-readers, defaults to 'Toggle navigation', can be overridden e.g. for internationalization.

navbarGroup

The $$.navbarGroup() method creates a ul tag decorated with
the Bootstrap "nav" and "navbar-nav" classes.
This should be used as a container for groups of $$.li() tags inside a $$.navbar().
In addition to standard tag attributes, it accepts the attribute "align" with values
"right" and "left", to do right- and left-alignment of the items (using Bootstrap's
"navbar-right", "navbar-left").
Example:

navbarForm

The $$.navbarForm() method creates a form tag
decorated with the Bootstrap "navbar-form" class.
This should be used as a container for form-groups and form items.
In addition to standard tag attributes, it accepts the attribute "align" with values
"right" and "left", to do right- and left-alignment of the items (using Bootstrap's
"navbar-right", "navbar-left").

pagination

The $$.pagination() method creates a ul tag decorated with the Bootstrap "pagination" class.

panel

The $$.panel() method creates a div tag decorated with the Bootstrap "panel-body" class,
wrapped in a div decorated with the Bootstrap "panel" class.
Pass it DOM objects in either the "heading" or "footer" attributes
to embed them within a div with the Bootstrap "panel-heading" or "panel-footer" class.

pageHeader

The $$.pageHeader() method creates a div tag decorated with the Bootstrap "page-header" class.

plain

The $$.plain object provides an alternate means of access to the plain HTML tag generators.
For tag names that also have Bootstrap decoration classes of the same name,
use $$.name() for the Bootstrap version, and $$.plain.name() for the plain HTML version.
Use this to get plain versions of button, form, input, label, and table tags.

spanLabel

The $$.spanLabel() method creates a span tag decorated with the Bootstrap "label" class,
and optionally with "label-*" classes for sizing and context.

thumbnail

The $$.thumbnail() method creates a div tag decorated with the Bootstrap "thumbnail" class.

well

The $$.well() method creates a div tag with class "well",
to make Bootstrap's simple well effect.

Bootstrap Attributes

We define a few special attributes that can be passed to
most tag factory functions, to handle certain Bootstrap formatting features.

bgcontext

Sets the "bg-*" background context-coloring class on the object.
Contexts defined by Bootstrap are
"default", "primary", "info", "success", "warning", and "danger".
For example:

$$.span({bgcontext: 'warning'})

will create a span with class "bg-warning".

context

Sets the appropriate context-coloring class on the object.
"text-", "btn-", "label-*", etc.
Contexts defined by Bootstrap are
"default", "primary", "info", "success", "warning", and "danger".
Also "text-muted" and "btn-link".
For example:

$$.button({context: 'info'})

will create a button with class "btn btn-info".

size

Sets the appropriate Bootstrap sizing class on the object.
Supported size names are "large" or "lg", "default" (the default),
"small" or "sm", and "xs" or "extra-small".
For example:

$$.button({size: 'large'})

will create a button with class "btn btn-lg".

Components

The tag factory functions described above give you
an easy way to build nice static content.
But here's where things get even more fun!
The Backstrap object also provides constructors for several
component classes that extend Backbone.View, to give you powerful
(and good-looking!) data-driven, model-bound DOM components.

The components are bound to either a Backbone Model or Collection.
(Actually, you will probably want to use
$$.Model, which extends Backbone.Model,
and $$.Collection, which extends Backbone.Collection,
to build your data models.)
The components then automatically re-render when the bound model
data changes.

For efficiency, you should use the factory functions, like $$.button(),
for static graphics. Use the object constructors, like $$.Button(),
to bind a graphic object to a data model whose value may change
over the life of the page.

Badge

Creates a Bootstrap badge (a span tag with class="badge") whose content is model-bound.
Give it a Model object and the name of the property you want to use as the
badge's content.
For example:

BasicNavbar

Creates a Bootstrap navbar whose buttons are model-bound.
By default, it will create a simple button for each element of the
provided Collection, using the model object's name, href, and label properties.
For example:

CollectionView

A generic Collection-aware view. Listens to
add, remove, and change events on the Collection,
and provides a basic rendering framework.
Extensions or instances of CollectionView may alter its behavior by overriding the methods
placeItem,
placeEmpty,
onItemAdded,
onItemChanged, and
onItemRemoved.
You may also provide the following attributes to the constructor:

model - the Collection to display

itemView - a View prototype for display of one item

itemViewOptions - optoins to pass to the itemView initializer

emptyContent - content to display when collection is empty

onItemClick - a click callback to be assigned to each itemView instance

Passing background: true makes it use the "bg-*" classes instead of "text-*".
You can also pass it a "tagName" attribute to create something other than a span.
The value of "content" defaults to "context".

DatePicker

Dropdown

Creates a Bootstrap dropdown menu whose buttons are model-bound.
By default, it will create a simple button for each element of the
provided Collection, using the model object's label and href properties.
Also supports header and divider elements.
The Dropdown is an extension of $$.List.
It additionally supports a "context" property for context-coloring;
a "labelContent" property (can be a string, or any DOM object) to display
as the button label; an "align" property to set the text alignment to "right" or "left",
a "dropup" property which, if true, makes the menu appear above the button instead of below it,
and a "type" property which can be set to "plain" (the default, good for use in navbars),
"button", or "split-button".
(see the Bootstrap example).
Example:

creates a dropdown with a header and three buttons; the last button is below a divider.
You can also use a "separator" property - "separator" is a synonym for "divider".

DropdownGroup

Creates an li tag which contains a ul populated with
the contents of the given Model. The model objects should contain 'href' and 'label' properties,
or you may pass an itemViewOptions option such as
"itemViewOptions: { content: 'hrefProperty', labelContent: 'labelProperty' }".
The DropdownGroup's labelContent option sets the content of a section header label.
The DropdownGroup displays a set of related choices in a dropdown menu, grouped together.

ModelView

A generic Model-aware view. Listens to change events on the Model, which cause it to re-render itself.

NavPills

Creates a Bootstrap "pills" nav whose buttons are model-bound.
By default, it will create a simple button for each element of the
provided Collection, using the model object's name, href, and label properties.
For example:

NavTabs

Creates a Bootstrap "tabs" nav whose buttons are model-bound.
By default, it will create a simple button for each element of the
provided Collection, using the model object's name, href, and label properties.
For example:

ProgressBar

ProgressBar creates a Bootstrap "progress" div, with model-bound progress bar(s).
"Model" property can be either a BackBone Model (for a single progress bar)
or a BackBone.Collection for (multiple stacked progress bars).
Model objects may contain context, min, max, labelled, and labelSuffix properties,
in addition to a content property which should be numeric.
Min and max default to 0 and 100; labelled defaults to false.

RadioGroup

Creates a group of radio buttons whose value is taken from the bound Model
and whose choices are taken from the bound Collection of alternatives.
For example:

TextField

TimePicker

A text area with a dropdown list of times.
Defaults to allowing choices in half-hour increments,
which can be changed by setting the 'interval' option (in minutes).
'Name' is the HTML name attribute for the form item.
Format defaults to 'hh:mm a'.
For example:

Backbone Extensions

Backstrap has objects for virtually all of the Backbone objects you'll need, too.

Events

$$.Events is a simple extension of Backbone.Events.

Model

$$.Model extends Backbone.Model,
adding a refresh() method and an autoRefresh option.
If autoRefresh is true, the Backstrap dispatcher will call model.fetch() on a regular basis
to refresh the model data from the server.
The interval is tunable (see dispatcher), and can be configured to slow down over time.

You can also set refreshOptions, which will be passed as options to fetch() during an autoRefresh
(and also when model.refresh() is called); and params, which will be used as URL parameters.
The jquery.ajax option "ifModified" is set to true for all refreshes.
For example:

Collection

$$.Collection extends Backbone.Collection,
adding a refresh() method and an autoRefresh option.
If autoRefresh is true, the Backstrap dispatcher will call collection.fetch() on a regular basis
to refresh the model data from the server.
The interval is tunable (see dispatcher), and can be configured to slow down over time.

You can also set refreshOptions, which will be passed as options to fetch() during an autoRefresh
(and also when collection.refresh() is called); and params, which will be used as URL parameters.
The jquery.ajax option "ifModified" is set to true for all refreshes.
For example:

View

Router

history

dispatcher

$$.dispatcher is a Backbone.Events object which provides the autoRefresh functionality for Models and Collections.
Tunable parameters are:

minInterval The base interval between refreshes (in seconds)

maxInterval The maximum interval between refreshes, after decay (in seconds)

decayFrequency How many refreshes to do at a particular interval before increasing the interval

decayFactor How much to increase the interval by, when decaying

LocalCache

$$.LocalCache is a simple cache mechanism that can be used by $$.Collection.
Whenever the collection fetches data from the server, a copy of the array of models is saved on the client
via the localStorage system, if available.
Its constructor takes the name under which data should be stored/retrieved.
If data exists in localStorage from a previous session, the collection will be populated with that data upon initialization.
Example usage:

noConflict

The $$.noConflict() method provides a mechanism for reverting the definition of $$.
Backstrap will attempt to register itself as a CommonJS module.
But when that functionality is not available
it defines the global $$ instead.
It is possible that your app would want to include
some other package that also uses the global $$.
In this case, load the Backstrap package after the other package;
you can then use $$.noConflict() to define some other variable
to hold the Backstrap object,
and revert the definition of $$ back to the other package.
For example:

var Backstrap = $$.noConflict();

Now $$ is whatever it was before you loaded Backstrap,
and you can use the variable Backstrap to access the Backstrap methods.
You might want to pick a shorter variable name, like $b.