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 ...

Get Mastering Backbone.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.