Backbone is a popular Javascript library that provides an MV* framework.
The three main types of objects in Backbone are:
- Models - Objects that includes data and behavior/interactivity related to that specific data
- Views - The visual representation of a model at a particular time through a DOM node (which may include children DOM nodes
- Collection - An array-like container that holds multiple models. Typically you will use a container to hold multiple instances of the same model class.
Guidelines on using Backbone:
General
- Backbone depends heavily on its eventing system which allows the developer to decouple different modules of the web app
Views
- The visual representation of a model through a DOM node
- Views can only be binded to one model or collection at most
- The view is only responsible for a few things:
- Rendering its binded model / collection as a DOM element
- Listening to DOM events (e.g. clicking a button) and invoking a method on its binded model
- Listening to Backbone events from its associated model/collection
- Views have a tree-like relationship with other views. While each view will only have one parent view (e.g. an AppView might instantiate a SectionView which renders a DOM node that fits into AppView's DOM node)
- The properties
template
andrender
are conventions in Backbone, however are not necessary - If a view is not binded to a model or collection and is not rendering dynamic content, it is worth examining whether the view should exist. can the static content be included in a parent view or just in the DOM as regular HTML?
Models
- Models do not have a relationship with their view. While views have a property such as
this.model
orthis.collection
, models cannot directly (or at least should not) directly access to their views
Collection
- Collections cannot hold attributes. They do not have the get or set methods, unlike models.
Events
- You can listen to multiple events in a single listener by listing multiple events with a space in between. For example, if you wanted the listener to invoke its callback function whenever a collection added or removed a model, you could create a listener like
this.collection.on('add change', callbackFunction, context)
- Backbone's event system was designed to mimic the DOM event system but there are some differences. One of them is that the DOM event system passes in a special type of DOM event object into the callback function.