fastread homefastrread library fastread menu

BackboneJS : Models and Views

Tutorial by:Sumit Chauhan      Date: 2016-08-12 01:02:52

❰ Previous Next ❱

Models and Views

Model-View Separation.

The single most important thing that Backbone can help you with is keeping your business logic separate from your user interface. When the two are entangled, change is hard; when logic doesn't depend on UI, your interface becomes easier to work with.

Model
  • Orchestrates data and business logic.
  • Loads and saves from the server.
  • Emits events when data changes.
View
  • Listens for changes and renders UI.
  • Handles user input and interactivity.
  • Sends captured input to the model.

A Model manages an internal table of data attributes, and triggers "change" events when any of its data is modified. Models handle syncing data with a persistence layer — usually a REST API with a backing database. Design your models as the atomic reusable objects containing all of the helpful functions for manipulating their particular bit of data. Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.

A View is an atomic chunk of user interface. It often renders the data from a specific model, or number of models — but views can also be data-less chunks of UI that stand alone. Models should be generally unaware of views. Instead, views listen to the model "change" events, and react or re-render themselves appropriately.

Collections

Model Collections.

A Collection helps you deal with a group of related models, handling the loading and saving of new models to the server and providing helper functions for performing aggregations or computations against a list of models. Aside from their own events, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection.

API Integration

Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection with the url of your resource endpoint:

var Books = Backbone.Collection.extend({
  url: '/books'
});

The Collection and Model components together form a direct mapping of REST resources using the following methods:

GET  /books/ .... collection.fetch();
POST /books/ .... collection.create();
GET  /books/1 ... model.fetch();
PUT  /books/1 ... model.save();
DEL  /books/1 ... model.destroy();

When fetching raw JSON data from an API, a Collection will automatically populate itself with data formatted as an array, while a Model will automatically populate itself with data formatted as an object:

[{"id": 1}] ..... populates a Collection with one model.
{"id": 1} ....... populates a Model with one attribute.

However, it's fairly common to encounter APIs that return data in a different format than what Backbone expects. For example, consider fetching a Collection from an API that returns the real data array wrapped in metadata:

{
  "page": 1,
  "limit": 10,
  "total": 2,
  "books": [
    {"id": 1, "title": "Pride and Prejudice"},
    {"id": 4, "title": "The Great Gatsby"}
  ]
}

In the above example data, a Collection should populate using the "books" array rather than the root object structure. This difference is easily reconciled using a parse method that returns (or transforms) the desired portion of API data:

var Books = Backbone.Collection.extend({
  url: '/books',
  parse: function(data) {
    return data.books;
  }
});

View Rendering

View rendering.

Each View manages the rendering and user interaction within its own DOM element. If you're strict about not allowing views to reach outside of themselves, it helps keep your interface flexible — allowing views to be rendered in isolation in any place where they might be needed.

Backbone remains unopinionated about the process used to render View objects and their subviews into UI: you define how your models get translated into HTML (or SVG, or Canvas, or something even more exotic). It could be as prosaic as a simple Underscore template, or as fancy as the React virtual DOM. Some basic approaches to rendering views can be found in the Backbone primer.

Routing with URLs

Routing

In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share. Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.

❰ Previous Next ❱


BackboneJS

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website