Search code examples
meteorspacebars

Meteor: getting the HTML element which is using a global helper


Is it possible to know the HTML element which is invoking a global helper?

I have this blaze template:

<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>

and so it'd be useful a helper like this:

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

where I want this to be the invoking HTML element instead of template's data context.

Is there a way to access the element? I know I could use this.$('#pencil') but it's useless since the id it's exactly what I want to know.


Solution

  • You can work around this problem by passing the tool name as an argument for the helper:

    <a id="pencil" class="{{toolIsActive 'pencil'}}">Pencil</a>
    
    UI.registerHelper('toolIsActive', function(tool) {
      return (tool === currentTool) ? 'active' : '';
    });
    

     


    Since this sort of helper is useful in many different parts of the application, you can make an universal one instead:

    <a id="pencil" class="{{classIfEqual 'pencil' currentTool 'active'}}">Pencil</a>
    
    UI.registerHelper('classIfEqual', function(a, b, className) {
      return (a === b) ? className : '';
    });