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.
Get the template:
$("#my-template").html()
Compile the template:
_.template($("#my-template").html())
Get data from the model:
var data = this.model.toJSON()
Render the template with model data:
renderedHtml = this.template(data)
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...