Javascript 主干模板法。为什么我们要传递一个模型?

Javascript 主干模板法。为什么我们要传递一个模型?,javascript,backbone.js,underscore.js,underscore.js-templating,Javascript,Backbone.js,Underscore.js,Underscore.js Templating,我不明白为什么要将model.toJSON()传递到此模板中: 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

我不明白为什么要将model.toJSON()传递到此模板中:

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
  }
});
// creates a template function
var templateFunc = _.template("<span><%= name %></span>");

// render the template using the passed data
templateFunc({ name: "Émile" }); // <span>Émile</span>
这个例子来自于此

this.template(this.model.toJSON())
让我感到困惑。模板方法似乎不接受参数,对吗?发生了什么?

将模板字符串作为参数(可选设置对象),并返回一个新的预编译模板函数,该函数将对象作为参数

此对象是模板中使用的数据:

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
  }
});
// creates a template function
var templateFunc = _.template("<span><%= name %></span>");

// render the template using the passed data
templateFunc({ name: "Émile" }); // <span>Émile</span>
返回模型的浅层副本或
属性
散列

要达到上述示例的等效效果,请执行以下操作:

var model = new Backbone.Model({ name: "Émile" });
templateFunc(model.toJSON()); // <span>Émile</span>
如果传递了数据对象,它不会返回函数,而是直接返回呈现的模板字符串

_.template('This is <%= val %>.', { val: "deprecated" });
// This is deprecated.
\uu0.template('This is.',{val:'deprecated'});
//这是不赞成的。

哦,我明白了
.template($('#item template').html())
返回一个函数:
function(a){returne e.call(this,a,b)}
@Jwan622确切地说,它有时看起来很混乱,因为主干视图有一个
template
属性,我们通常用
.template
的返回值填充它。啊,我现在明白了。谢谢