2014-07-21 46 views
1

是否有可能知道調用全局幫助程序的HTML元素?流星:獲取使用全局幫助程序的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這正是我想知道的。

回答

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 : ''; 
}); 
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結構在多個地方,然後,如果你想添加更多的工具,你只必須將其添加到一個地方。

+0

即使我最終使用了你的解決方案(似乎更加靈活,對我而言更少冗餘),我查看了@Hubert的回覆,因爲它似乎更適合我的具體問題(雖然不是我所要求的)。非常感謝。 :-) – physiocoder