javascript - 模板中的 Backbone 模型对象

标签 javascript backbone.js underscore.js

在我的主干模型中,我有一个像这样的对象

 {
   lunsize: "big",
   type: {mike: "who", james: "him"}
}

在我的模板中,当我这样做时

<% _.each(type, function(sip) { %>
<%= sip %>

<% }); %>

我得到了预期的结果,即 whohim

想知道如何循环整个模型本身而不仅仅是类型字段。

PS:我正在使用toJSON()将我的模型转换为js对象

最佳答案

您可以传递templatevariable设置。这指示下划线创建一个需要给定名称的变量的函数,而不是使用 with 将范围更改为传递的数据对象的默认行为。

创建 Backbone 模板时,传递变量名称:

_.template(yourTemplate, null, {variable: "data"});

然后您可以通过模板内的变量名称访问数据:

<% _.each(data, function (val, key) { %>
  ...
<% }); %>

由于 with 相当慢,因此它具有渲染速度更快的额外优势。来自 the underscore docs :

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. This can significantly improve the speed at which a template is able to render.

关于javascript - 模板中的 Backbone 模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618872/

相关文章:

javascript - 当 URL 更改时, Backbone 单页应用程序会向用户发出警报

node.js - 使用 Mongoose 从 MongoDB 获取数据

Javascript无限类别深度树

php - WYSIWYG drupal 插件中 tinymce 的文本字段名称

javascript - 将具有动态变量数的参数对象转换为多个参数

javascript - window.localStorage() 设置语言首选项

android - 平板电脑/手机上的 backbone.js 和调试

javascript - this.$something = this.$ ('something' ) 是什么意思?

backbone.js - 如何将所有模板放在不同的 HTML 文件中,如 "AppTmpl.html"以及如何访问主干中的这些模板?

javascript - 如何将 select 值传递给另一个函数并根据传递的值从 Json 获取数据?