Search code examples
javascriptmeteorclosuresmeteor-helper

Meteor JS: Organizing Code for Sharing Code Between Template Helpers


Inside my Meteor JS Project's client/templates/pages folder I have these files:

1.) admin_add_product.html and admin_add_product.js

2.) admin_edit_product.html and admin_edit_product.js

Inside both admin_add_product.js and admin_edit_product.js I have the same exact code that I use for both files:

var ucwords = function(str)
{
  return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
};


var editForDB = function(str){

  return ucwords(str.trim());
}

var makeHidden = function(object){
  object.addClass('hidden');
}

var removeHidden = function(object){
  object.removeClass('hidden');
}

var makeDisabled = function(object){
  object.addClass('disabled');
}

var removeDisabled = function(object){
  object.removeClass('disabled');
}

I would like to organise my code so that I don't REPEAT any code unnecessarily. I wish to put the above snippet of code somewhere where I can share between Template helpers (in this case between admin_add_product.js and admin_edit_product.js) so if ever I do need to edit it I just need to edit it in one place rather than two or more....

I already tried Template.registerHelper but I have found that that only works inside the .html file.........

How do I organise my code in Meteor JS to do this?

Is this even possible in Meteor JS given that each template helper file is supposedly enclosed inside a function(){} closure???


Solution

  • Variables declared with var have a file scope, and are indeed inside a closure like you mentioned. However, if you declare new variables without the var keyword, they are accessible throughout your project (given you load files in the right order), as Meteor declares these variables outside the closure.

    In your case the solution is to declare your form functions without var, or maybe better declare a new object without var and put them as methods in there:

    FormHelpers = {};
    
    FormHelpers.ucwords = function(str)
    {
      return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
    };
    
    ...
    

    You can then use these helpers in both you add and edit tenplates, or anywhere else you need them.

    More info on namespacing in the Meteor docs.