javascript - 主干模板方法。为什么我们要传入一个模型?

标签 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 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 the with statement. However, you can specify a single variable name with the variable 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/

相关文章:

javascript - 如何与angular js联合获取最新记录

javascript - 有什么方法可以使用 underscore.js 重命名 js 对象键

JavaScript getBoundingClientRect() 在滚动时发生变化

javascript - 引用错误 : KeyframeEffect is not defined in paper component

Backbone.js `listento` 未触发过滤集合

javascript - Backbone Marionette : using emptyView for loading

javascript - 主干 View 继承

AngularJS - 错误 '_' 未定义

javascript - 是否有 "special"URL 参数强制 SWFObject 显示替代内容?

javascript - 如何在 Perl 中打开 javascript 对象?