32

I want to create an application in Meteor, from what I understand the manual it first loads which are in subdirectories, and then follows the alphabetical order. My file structure is like this ...

/server
/lib
/client
    /lib
        game.js -> already starts declaring the function "makeBoard(){}"
    /template.js -> where the function "makeBoard()" is called.

thus appears that the error function "makeBoard()" does not exist, only works if I declare in the same file where I want to call it. Even when I move the file "game.js" to the same directory where "template.js", it happens. How should I correctly make references to resources that are in different files on Meteor?

rogeriojlle
  • 1,046
  • 1
  • 11
  • 19

2 Answers2

52

Using a globally defined variable, as avital suggests, will work, but is not a recommended code design choice (see JS mistake 1 listed here).

Instead in your lib directory you could create a file with:

Meteor.myFunctions = {
...
    makeBoard : function() { ... },
...
}

Then in any other js file you could call Meteor.myFunctions.makeBoard(). This should be done in the lib directory because Meteor guarantees the js files in lib are loaded before other directories, so your function will already be loaded.

Shwaydogg
  • 2,499
  • 27
  • 28
  • 3
    Very clever. If you are sharing functions from multiple files this will make it possible: Meteor['myFunctions'] = Meteor['myFunctions'] || {}; Meteor['myFunctions']['createinstanceclass'] = function () { return new instanceclass(); } Meteor['myFunctions'] = Meteor['myFunctions'] || {}; Meteor['myFunctions']['createsolutionclass'] = function () { return new solutionClass(); } If you agree please add it to your answer; if not please explain how to do it better :) – Rune Jeppesen Sep 11 '15 at 21:18
  • THANK YOU. Finally got some custom server side codes running. I tried running this on the client, and it DID NOT work, as expected. Fantastic. – Andy Oct 18 '16 at 15:59
47

Define the function with makeBoard = function() { ... }.

Functions defined with function foo() { ... } are local to the file, as are variables defined with var bar = ....

avital
  • 1,542
  • 11
  • 15
  • With the EMCA6 release, and specifically the `"use strict"` tag for javascript code this solution doesn't compile. I strongly suggest @Shwaydogg solution for that reason. – firescar96 Aug 24 '15 at 05:31
  • This works CLIENT SIDE only. Please see Shwaydogg's answer for a SERVER side fix using Meteor.MyFunction.Method() – Andy Oct 18 '16 at 15:59