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
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
I think the issue arises when I use coffeescript. When I convert my coffeescript files to js files everything seems to work.
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.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With