【问题标题】:Meteor: getting the HTML element which is using a global helperMeteor:获取使用全局帮助器的 HTML 元素
【发布时间】:2014-09-11 20:17:52
【问题描述】:

是否有可能知道调用全局助手的 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 这正是我想知道的。

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

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

    <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 : '';
    });
    

    【讨论】:

      【解决方案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 结构,然后如果您想添加更多工具,您只需在一个地方添加它。

      【讨论】:

      • 即使我最终使用了您的解决方案(对我来说似乎更灵活且更少冗余),我检查了@Hubert 回复是否已接受,因为它似乎更适合我的具体问题(尽管不完全是我要求)。非常感谢两位。 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2020-08-22
      • 2011-10-21
      • 2014-01-08
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多