Search code examples
node.jsmeteormeteor-blazemeteoritemeteor-helper

How to access elements in the current template in meteor?


I have a template like this,

<template name = "foo">
    <p id="loading" >LOADING...</p>
    <p> {{theResult}} </p>
</template>

This is how I create foos,

 // foos = [a, b, c, d]. With each button click I add a new item to the array
 {{#each foos}}
    {{> foo .}}
 {{/each}}

And how a foo works,

Template.foo.created = function(){
    var name = Template.currentData();
    api_call(name, function(err, result){
        Session.set(name, result);
    }); 
}  

Template.foo.helpers({
        'theResult': function(){
            var name = Template.currentData();
            if(Session.get(name)) {
                $("#loading").hide();
                return Session.get(name);
            } else {
                return "";
            }
        }
    })

So my expectation is to when the data came from the api_call, to hide "LOADING..." para, and to show the result in theResult.

The result is showing correctly. My problem is "LOADING..." is only get hidden on the top most foo. Not the other ones.

How can I fix this?

EDIT: As suggested instead of,

$("#loading").hide();

I used,

Template.instance().$("#loading").hide();

This didn't work too :)


Solution

  • This is how I'd do it

    Template... if theResult is undefined, the else path will be rendered.

    <template name="foo">
        {{#with theResult}}<p> {{this}} </p>
        {{else}}<p id="loading" >LOADING...</p>
        {{/with}}
    </template>
    

    Javascript... theResult is a simple Session.get call

    Template.foo.helpers({
        theResult: function(){
            var name = Template.currentData();
            return name && Session.get(name);
        }
    });