Reused part of code in Meteor JS

I have this code

Template["product"].helpers(
  "variant": ->
    variant_value = Session.get("variant")
    if variant_value
      return variant_value
    else
      Session.set("variant",@lowest_variant())
  "isSelected": ->
    if @variant() == opt1_name
      return true
    else return false

I want to used variant method inside isSelected. The code above does not work. Any idea how to create a function so that it can be used to different helper methods?

You can add general function on top of that file and use it locally in that file.

Roughly:

getVariant = ->
  variant_value = Session.get('variant')
  if variant_value
    return variant_value
  else
    Session.set('variant',@lowest_variant())
    
Template['product'].helpers(
  'variant': -> getVariant()
  'isSelected': ->
    if getVariant() == opt1_name
      return true
    else return false

You can also add a function to the template and then use that in your helpers and events. Here is a quick demo with the standard hello template

Template.hello.created = function() {
  this.myOwnFunction = function() {
    // whatever shared code
    return new Date();
  }
};

Template.hello.helpers({
  counter: function () {
    var template = Template.instance();
    console.log( template.view.name+'.helpers.counter',template.myOwnFunction() );
    return Session.get('counter');
  }
});

Template.hello.events({
  'click button': function (e,template) {
    // increment the counter when button is clicked
    console.log(template.view.name+'.events', template.myOwnFunction() );
    Session.set('counter', Session.get('counter') + 1);
  }
});

1 Like

@rova
I tried your idea but it does not work. I got this code

get_price: () ->
  price = Session.get('price')
  if price
    return price
  else
    Session.set('price', @lowest_price())
    return @lowest_price()


Template['product'].helpers(
  'price': -> get_price()
)

but it will have an error Exception in template helper: ReferenceError: get_price is not defined. Do you have any idea why?

You made a little mistake here: get_price: () -> should be get_price = () -> with the ‘=’ sign.

1 Like

@rova thanks it works!

You’re welcome. Glad it worked!

1 Like