I can't figure out why we are passing in a model.toJSON() into this template:
app.TodoView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#item-template').html()),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this; // enable chained calls
}
});
The example comes from this tutorial.
this.template(this.model.toJSON())
is the confusing part to me. The template method doesn't seem to take in an argument right? What is going on?
Underscore
_.template
function takes a template string as argument (and optionally a settings object) and returns a new pre-compiled template function which takes an object as an argument.This object is the data used within the template:
model.toJSON()
returns a shallow copy or theattributes
hash of the model.To achieve the equivalent of the above example:
For Underscore.js before v1.7, the template function signature was a little different:
If a data object was passed, it didn't returned a function, but returned the rendered template string directly.