Views & Templates

In notebook:
FrontEndMasters BackboneJS
Created at:
2016-06-09
Updated:
2016-06-10
Tags:
libraries JavaScript

Backbone Views

  • An object that manages the presentation of a model
  • NOT just the HTML that gets rendered to the DOM
  • Manages events for its markup

Define a view

  var SongView = Backbone.View.extend({
  render: function(){
    var template = _.template($('#song_template').html());
    var markup = template(this.model.toJSON());
    
    this.$el.html(markup).appendTo('#songs');
  }
});

var song = new Song({artist: "Death Cab for Cutie", song: "Codes & Keys"});
song.view = new songView({model:song});
song.view.render();

Templating 

Template: an HTML fragment that accepts a JavaScript object to fill in its missing data pieces.

Every templating library is doing this. 
Many libraries follow this pattern (this EJS):
  <script type="html/template" id="song_template">
  <li class="song">
    Title: <%= title %>
    Artist: <%= artist %>
  </li>
</script>
note:  the ​type​ attribute is new definition that is not in the spec.

This pattern (the JS block and the HTML template) is not recommended for production. It uses very expensive methods (reading the template element from the DOM).

Underscore has a great templating engine (by John Ressig). It uses string concatenation. Mentions pre-compilation.