Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
Free Lancer Avatar asked Oct 06 '13 02:10

Free Lancer


People also ask

Where are JavaScript functions usually placed?

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

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.

like image 159
Hubert OG Avatar answered Sep 29 '22 06:09

Hubert OG