Search code examples
meteorproject-structure

Where to put helper methods used in events for multiple Meteor templates


I know that I can access methods across files by omitting var, but what is the "best practices" project directory structure for defining helper methods that are used by template events across different templates.

For example, I have:

template1.js:

Template.template1.events({
  'event': function () {
    helper();
   }
});

template2.js:

Template.template2.events({
  'event': function () {
    helper();
   }
});

Solution

  • One problem with Meteor's "share code across files with globals" approach is that when you're looking at the file where a function is used, you don't know where the function is defined. I prefer to define a single global variable in each file which needs to export variables. That variable has the same name as the file, with an initial capital (or some other naming convention which identifies it as an "export object"). Exports are stored as properties of that object. So you might create a file named globalHelpers.js:

    GlobalHelpers = {};
    GlobalHelpers.helper = function () {
        // ...
    };
    

    And then use it in other files with GlobalHelpers.helper(). If you look at this code later, you know to look in globalHelpers.js to find the helper function.

    If a file exports a single class or collection then it's okay to just use that object as the export object. So instead of things.js with Things = {}; Things.Things = new Mongo.Collection... you can just do Things = new Mongo.Collection....

    You might need to place the file in a lib directory so it loads before the other files.

    Don't register it with Template.registerHelper unless you want to call it directly from templates with {{ }} calls.