我不明白为什么我们要将 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
}
});
例子来自这个tutorial .
this.template(this.model.toJSON())
是让我感到困惑的部分。模板方法似乎没有参数,对吗?这是怎么回事?
最佳答案
Underscore _.template
function将模板字符串作为参数(以及可选的设置对象)并返回一个新的预编译模板函数,该函数将对象作为参数。
此对象是模板中使用的数据:
// creates a template function
var templateFunc = _.template("<span><%= name %></span>");
// render the template using the passed data
templateFunc({ name: "Émile" }); // <span>Émile</span>
By default,
template
places the values from your data in the local scope via thewith
statement. However, you can specify a single variable name with thevariable
setting._.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
model.toJSON()
返回模型的浅拷贝或 attributes
散列。
实现上面例子的等价物:
var model = new Backbone.Model({ name: "Émile" });
templateFunc(model.toJSON()); // <span>Émile</span>
对于 Underscore.js before v1.7 ,模板函数签名有点不同:
_.template(templateString, [data], [settings])
如果传入的是数据对象,则不返回函数,而是直接返回渲染后的模板字符串。
_.template('This is <%= val %>.', { val: "deprecated" });
// This is deprecated.
关于javascript - 主干模板方法。为什么我们要传入一个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41147890/