【问题标题】:Pass in parameter to handlebars helper将参数传递给车把助手
【发布时间】:2013-08-14 08:50:20
【问题描述】:

所以我有一个非常简单的车把助手 -

Handlebars.registerHelper('selectRow', (rowIndex, selectedIds) ->
  console.log 'row index'
  console.log rowIndex
  console.log selectedIds
  isSelected = _.indexOf(rowIndex, selectedIds)
  if isSelected > -1 
    return 'class="row-selected"'
)

我有这个车把代码 -

<div class="title">{{ title }}</div>
<hr/>
<table cellspacing="0" cellpadding="0">
  <thead>
    {{#each columns}}
    <th class="col-heading" data-heading="{{ this }}">{{ this }}</th>
    {{/each}}
  </thead>
  <tbody>
    {{#each rows}}
        <tr {{#selectRow @index selected }}>
          {{#each this}}
          <td>
            {{this}}
          </td>
          {{/each}}
        </tr>
      {{/selectRow}}
    {{/each}}

  </tbody>
</table>

所选参数始终未定义。如果我在其他任何地方添加一个 {{ selected }},它会显示一个数组,正如您从下面看到的那样,它应该 -

data = @model.data()
selected = @model.get('selection').get('selected')
@$el.html(@tableContentsTemplate({
  columns: @model.get('columns')
  rows: data
  title : @model.get('title')
  selected: JSON.stringify(selected)
}))

如何将所选参数正确传递给我的助手?

【问题讨论】:

    标签: javascript coffeescript underscore.js handlebars.js


    【解决方案1】:

    您在 Handlebars each 循环中使用了 selected 变量,所以我想 selected 不在范围内。

    【讨论】:

      【解决方案2】:

      我认为您对_.indexOf 的工作原理有点困惑。来自fine manual

      indexOf _.indexOf(array, value, [isSorted])

      返回 value 可以在 array 中找到的索引,如果 中不存在 value,则返回 -1数组

      因此,您要搜索的数组selectedIds 应该是第一个参数,而您要搜索的元素是第二个参数。也许你的意思是:

      isSelected = _.indexOf(selectedIds, rowIndex)
      

      或更好(IMO):

      isSelected = _(selectedIds).indexOf(rowIndex)
      

      我通常发现使用_() 函数会产生更清晰的代码。

      另外,{{#selectRow @index selected }} 不应该是{{selectRow @index selected}} 吗?一个领先的# 应该引入一个块,但你的助手不是写成块助手。

      一旦上述两个问题都得到解决,对我来说似乎发生了一些明智的事情:http://jsfiddle.net/ambiguous/pkVZc/1/

      【讨论】:

        猜你喜欢
        • 2013-09-25
        • 2014-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        相关资源
        最近更新 更多