主干模板方法.为什么我们传入一个模型? [英] Backbone template method. Why are we passing in a model?
问题描述
我不明白为什么我们将 model.toJSON() 传入这个模板:
app.TodoView = Backbone.View.extend({tagName: 'li',模板:_.template($('#item-template').html()),渲染:函数(){this.$el.html(this.template(this.model.toJSON()));返回这个;//启用链式调用}});
这个例子来自这个教程.
this.template(this.model.toJSON())
对我来说是令人困惑的部分.模板方法似乎没有接受参数,对吗?这是怎么回事?
Underscore _.template
function 接受一个模板字符串作为参数(和可选的设置对象)并返回一个新的预编译模板函数,该函数接受一个对象作为参数.
这个对象是模板中使用的数据:
//创建模板函数var templateFunc = _.template("<%= name %>");//使用传递的数据渲染模板templateFunc({ name: "Émile" });//<span>埃米尔</span>
<块引用>
默认情况下,template
将数据中的值放置在本地通过 with
语句作用域.但是,您可以指定单个带有 variable
设置的变量名称.
_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
model.toJSON()
返回浅拷贝或attributes
模型的哈希值.
实现上面例子的等效:
var model = new Backbone.Model({ name: "Émile" });templateFunc(model.toJSON());//<span>埃米尔</span>
<小时>
对于 v1.7 之前的 Underscore.js,模板函数签名有点不同:
_.template(templateString, [数据], [设置])
如果传入一个数据对象,它没有返回函数,而是直接返回渲染后的模板字符串.
_.template('This is <%= val %>.', { val: "deprecated" });//这已被弃用.
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:
// 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()
returns a shallow copy or the attributes
hash of the model.
To achieve the equivalent of the above example:
var model = new Backbone.Model({ name: "Émile" });
templateFunc(model.toJSON()); // <span>Émile</span>
For Underscore.js before v1.7, the template function signature was a little different:
_.template(templateString, [data], [settings])
If a data object was passed, it didn't returned a function, but returned the rendered template string directly.
_.template('This is <%= val %>.', { val: "deprecated" });
// This is deprecated.
这篇关于主干模板方法.为什么我们传入一个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!