1

是否有可能知道调用全局助手的 HTML 元素?

我有这个火焰模板:

<template name="tools">
  <div>
    <a id="pencil" class="{{toolIsActive}}">Pencil</a>
    <a id="shape" class="{{toolIsActive}}">Shape</a>
    <a id="poly" class="{{toolIsActive}}">Polygon</a>
    <a id="arrow" class="{{toolIsActive}}">Arrow</a>
  </div>    
</template>

所以像这样的助手会很有用:

UI.registerHelper('toolIsActive', function() {
    return (this.id === currentTool) ? 'active' : '';
});

我想this成为调用 HTML 元素而不是模板的数据上下文。

有没有办法访问元素?我知道我可以使用this.$('#pencil'),但它没用,因为id它正是我想知道的。

4

2 回答 2

3

您可以通过将工具名称作为帮助程序的参数传递来解决此问题:

<a id="pencil" class="{{toolIsActive 'pencil'}}">Pencil</a>

UI.registerHelper('toolIsActive', function(tool) {
  return (tool === currentTool) ? 'active' : '';
});

 


由于这种帮助器在应用程序的许多不同部分都很有用,因此您可以创建一个通用的帮助器:

<a id="pencil" class="{{classIfEqual 'pencil' currentTool 'active'}}">Pencil</a>

UI.registerHelper('classIfEqual', function(a, b, className) {
  return (a === b) ? className : '';
});
于 2014-07-21T11:48:45.520 回答
2

另一种方法,可以在将来更容易添加更多工具:

<template name="tools">
  <div>
    {{#each tools}}
      <a id="{{id}}" class="{{toolIsActive}}">{{humanName}}</a>
    {{/each}}
  </div>
</template>
Template.tools.helpers({
  tools: [
    {id: "pencil", humanName: "Pencil"},
    {id: "shape",  humanName: "Shape"},
    {id: "poly",   humanName: "Polygon"},
    {id: "arrow",  humanName: "Arrow"}
  ],
  toolIsActive: function() {
    return (this.id === currentTool) ? "active" : ""
  }
});

您可能会tools在多个地方使用该结构,然后如果您想添加更多工具,您只需在一个地方添加它。

于 2014-07-21T13:43:56.100 回答