How do I make sure my subscription is ready before looking for it inside the helper?

I want to do something very simple, namely turn the value of a field in my database into a variable in my helper. The document looks like this:

{
  hero: "Simon Belmont",
  universe: "Castlevania",
  items: ["Whip", "Cross", "Oak Stake"]
}

      

In a helper, I want to do something similar to this:

var selectedHeroId = Session.get('whichHeroSelected')
var heroItems = Heroes.findOne({_id: selectedHero}).items

      

This, however, proved to be very fickle. Sometimes he complains that he is items

not defined. Oddly enough, it works when I call a variable items

, but not when I call it heroItems

or itemsArray

.

So, I'm looking for a way to make sure that it is Heroes

signed before looking for things in the database. I subscribe to it in the Iron Router feature by the waitOn

way.

+3


source to share


1 answer


It looks like you just need guard :



Template.myTemplate.helpers({
  items: function() {
    var selectedHero = Heroes.findOne(Session.get('whichHeroSelected'));
    return selectedHero && selectedHero.items;
  }
});

      

+2


source







All Articles