Book Image

Mastering Backbone.js

By : Abiee Echamea
Book Image

Mastering Backbone.js

By: Abiee Echamea

Overview of this book

Backbone.js is a popular library to build single page applications used by many start-ups around the world because of its flexibility, robustness and simplicity. It allows you to bring your own tools and libraries to make amazing webapps with your own rules. However, due to its flexibility it is not always easy to create scalable applications with it. By learning the best practices and project organization you will be able to create maintainable and scalable web applications with Backbone.js. With this book you will start right from organizing your Backbone.js application to learn where to put each module and how to wire them. From organizing your code in a logical and physical way, you will go on to delimit view responsibilities and work with complex layouts. Synchronizing models in a two-way binding can be difficult and with sub resources attached it can be even worse. The next chapter will explain strategies for how to deal with these models. The following chapters will help you to manage module dependencies on your projects, explore strategies to upload files to a RESTful API and store information directly in the browser for using it with Backbone.js. After testing your application, you are ready to deploy it to your production environment. The final chapter will cover different flavors of authorization. The Backbone.js library can be difficult to master, but in this book you will get the necessary skill set to create applications with it, and you will be able to use any other library you want in your stack.
Table of Contents (12 chapters)
11
Index

ModelView


The simplest implementation is to render a single model; it's a very straightforward algorithm. Extract data from the model and use a template engine to make the actual render with the data; finally, attach the result in the DOM:

class MyView extends Backbone.View {
  constructor(options) {
    super(options);
    template: _.template($("#my-template").html());
  }
  
  render() {
       var data = this.model.toJSON();
    var renderedHtml = this.template(data);
    this.$el.html(renderedHtml);
    return this;
  }
}

In the following code we can identify five steps to rendering the view.

  1. Get the template:

    $("#my-template").html()
    
  2. Compile the template:

    _.template($("#my-template").html())
    
  3. Get data from the model:

    var data = this.model.toJSON()
    
  4. Render the template with model data:

    renderedHtml = this.template(data)
    
  5. Put the result on the DOM:

    this.$el.html(renderedHtml)
    

Note that we return this in the render() method; this is useful for chaining calls. These steps are common for all...