Search code examples
javascriptmeteorhandlebars.jsmeteor-blaze

how to select helper tags in events (handlebars/meteor)


I have a reference to a helper called 'number' in my HTML:

Number of Entries: {{number}}

and that helper just counts how many entries are in my database

Template.general.helpers({
    number: function(){
        return collectionName.find().count()
    }
});

I'm trying to make an event so that when I click on the {{number}} element it will return that number to the console and I can't figure out how to get it to respond to the click at all, let alone respond with the number

Template.general.events({
    'click .number': function(){
        console.log('hi');
    }
});

Solution

  • Since you want to easily have the value available in the event handler and avoid unnecessary re-computations, it is possible to use a {{#with}} clause that sets the data context for its content, which is accessible via the dot ({{.}}) symbol.

    {{#with number}}
      <span class="number">
        Number of Entries: {{.}}
      </span>
    {{/with}}
    

    This gives your handler both a class to hook to and the data context that will make the value easily accessible.

    Template.general.events({
      'click .number': function(e, tpl){
        console.log('the number is', this); //"this" is the data context
      }
    });
    

    Which will log the relevant count to the console.