Free Lancer
Free Lancer

Reputation: 1000

Where to place javascript functions in Meteor applications

In Meteor we normally attach javascript functions to Templates. Where do we place standard javascript functions?

For instance, in one of my apps I have a UserInfo.js file which has a bunch of javascript functions for handling users logging in and getting user information.

Below are two of my functions in UserInfo.js

File is located in the client/scripts folder:

isAdminById = function(userId) {
  var user;
  user = Meteor.users.findOne(userId);
  return user && isAdmin(user);
};

isAdmin = function(user) {
  if (!user || typeof user === 'undefined') {
    return false;
  } else {
    return !!user.isAdmin;
  }
};

When I run the app and call isAdmin() from the browser console it says:

ReferenceError: isAdmin is not defined

---- Edit ----

It seems the problem was fixed temporarily when I placed the javascript file under the client/compatibility folder but now the issue has resurfaced. The only thing I remember changing was calling >> Meteor Reset

More Info:

I think the issue arises when I use coffeescript. When I convert my coffeescript files to js files everything seems to work.

Upvotes: 5

Views: 1497

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

You need to declare coffeescript variables as global with @:

@isAdmin = user -> ...

This is due to how Meteor variable shadowing works in connection with coffeescript automatic variable declaration.

Coffeescript by default does the "smart" variable declaration by itself - basically by placing var variableName in the first place in javascript where the variable is visible. In your case, this causes isAdmin to be declared by var in js, and therefore it's scoped to the file.

Using @ char supersedes this default behavior by binding the variable to this, global or window object instead.

Upvotes: 3

mquandalle
mquandalle

Reputation: 2598

Your code is correct, it's probably a load order problem.

Upvotes: 2

Related Questions