Linus
Linus

Reputation: 948

Meteor: Where to put common template functions (best practices)

Where should I put functions that are common for a specific template?

For example a function that is called from different events inside a template.

Is this still considered a helper, even though I don't want to invoke the function in my template like {{foo}}?

Upvotes: 2

Views: 715

Answers (1)

saimeunt
saimeunt

Reputation: 22696

If these functions are using the underlying template instance properties and methods, you can attach them to the instance, here is a simple example for a newsletter subscribe form :

HTML

<template name="newsletterForm">
  <form>
    <div class="alert {{alertClass}}">{{alertText}}</div>
    <div class="form-group">
      <label for="address">Email</label>
      <input id="address" type="email" class="form-control" name="address">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</template>

JS

Template.newsletterForm.created=function(){
  this.alertClass=new ReactiveVar("alert-primary");
  this.alertText=new ReactiveVar("Subscribe to our newsletter, we'll send you the best links each week !");
  //
  this.subscribeSuccess=function(){
    this.alertClass.set("alert-success");
    this.alertText.set("Thanks for subscribing !");
  };
  this.subscribeFailure=function(){
    this.alertClass.set("alert-warning");
    this.alertText.set("Could't subscribe you to the newsletter, please double-check your email address !");
  };
};

Template.newsletterForm.helpers({
  alertClass:function(){
    return Template.instance().alertClass.get();
  },
  alertText:function(){
    return Template.instance().alertText.get();
  }
});

Template.newsletterForm.events({
  "submit":function(event,template){
    event.preventDefault();
    //
    var address=template.$("[type='email']").val();
    Meteor.call("newsletterSubscribe",address,function(error,result){
      if(error){
        template.subscribeFailure();
        return;
      }
      template.subscribeSuccess();
      template.find("form").reset();
    });
  }
});

If they're not using any template instance specific properties, you can simply declare them as file-scoped functions :

function commonFunc(){
}

If these functions are not intended to use as helpers, I think it's unnecessary to declare them as such.

Upvotes: 2

Related Questions