简体   繁体   中英

Wait with rendering Meteor template helper until variable is available

I'm creating a location-based chat app in Meteor. Now I want to render only the chat messages which are in the users region. The TheRegion.region variable gets filled with an HTML5 geolocation request.

Template.locationchat.helpers({
  messages: function () {
    return Messages.find({location: TheRegion.region});
  }
});

The problem of this code is that the TheRegion.region variable is still null when this helper is called. Is there a way to run the helper in a callback of the geolocation function? Or run the template helper when the variable has a value?

I often find in Meteor that if you are waiting on a variable all you need is an if clause to protect yourself.

Try this:

  Template.locationchat.helpers({
    messages: function () {
        if(TheRegion.region)
            return Messages.find({location: TheRegion.region});
    }
  });

It doesn't feel natural, but usually it works. Give it a try.

That's because your variable isn't reactive.

In your onCreated:

TheRegion = new ReactiveDict();
TheRegion.set('region',undefined);

Now, region is always going to exist by the time it reaches the helper & when the value changes, your helper will rerun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM