Reused part of code in Meteor JS


I have this code

  "variant": ->
    variant_value = Session.get("variant")
    if variant_value
      return variant_value
  "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.


getVariant = ->
  variant_value = Session.get('variant')
  if variant_value
    return variant_value
  '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();

  counter: function () {
    var template = Template.instance();
    console.log('.helpers.counter',template.myOwnFunction() );
    return Session.get('counter');
  'click button': function (e,template) {
    // increment the counter when button is clicked
    console.log('.events', template.myOwnFunction() );
    Session.set('counter', Session.get('counter') + 1);


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

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

  '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.


@rova thanks it works!


You’re welcome. Glad it worked!