LOADING...

{{theResult}}

This is how I create foos, // " />

LOADING...

{{theResult}}

This is how I create foos, // " />

LOADING...

{{theResult}}

This is how I create foos, // "/>

How to access elements in the current template in meteor?

330 Views Asked by At

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

2

There are 2 best solutions below

0
Lucas Blancas On BEST ANSWER

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);
    }
});
3
saimeunt On

Thanks to Meteor templating engine, you can access a template scoped jQuery object that will only return elements within the corresponding template.

Template.foo.helpers({
  'someText': function(){
    var template = Template.instance();
    template.$('p').changeSomeattr();
    return Session.get('myPara');
  }
});