Search code examples
meteormeteor-blaze

Create a universal helper variable


Is there a way to create a variable at the top of template helpers to remove duplication.

In this particular situation I'm using var candidate = FlowRouter.getParam('id'); and I have to create the variable in each helper. I assume there is a better way.

professionalOverview: function() {
    var candidate = FlowRouter.getParam('id');
        return ProfessionalOverview.findOne({ candidateUserId: candidate });
    },
  candidateImg: function() {
    var candidateUserId = FlowRouter.getParam('id');

    return Files.findOne({ userId: candidateUserId });
  },

EDIT

Template.talentProfileNew.onCreated(function() {
    var self = this;
    self.autorun(function(){
        this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
    }
});

Template.talentProfileNew.helpers({
  candidate: function() {
    console.log(Template.instance().candidateUserId.get());

    return Meteor.users.findOne({_id: Template.instance().candidateUserId.get()});
  }
});

Solution

  • you could read it once in onCreated() and put it in a reactive var. e.g.

    Template.Foo.onCreated(function() {
        this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
    });
    
    Template.Foo.helpers({
        candidateImg() {
            return ProfessionalOverview.findOne({ userId: Template.instance().candidateUserId.get()});
        }
    });