Not able to use global functions inside event helpers

So I have defined some global function in a shared.js file, e.g.

diff = function(x, y) {
  return x * y
};

and am trying to access it inside a event handler helper function inside another file (cc.js):

'submit #clsubmit': function (event, templateInstance) {
		event.preventDefault();
		let x = form.querySelectorAll(':checked').length; //get number of tasks completed
		let y = 22 - numTasksCompleted; // tasks left to completed
               diff(x, y);
};

This is throwing a error as diff is not defined. Why is this not working? I have tried it with shared.js in the same directory as well as with it in the lib directory so that it is loaded first.

Thanks

This is by intent. All Meteor files are encapsulated so they do not pollute the global namespace. You can access your function, if you assign it to the window object. But I would recommend to do this only for one object which is named “app” or something like this. You then hook your functions into that object, so the global namespace keeps tidy.

Example:

File 1:


window.app = window.app || {};

window.app.diff = function(x, y) { ... }

File 2:

const {
   diff
} = window.app;

'submit #clsubmit': function (event, templateInstance) {
		event.preventDefault();
		let x = form.querySelectorAll(':checked').length; //get number of tasks completed
		let y = 22 - numTasksCompleted; // tasks left to completed
               diff(x, y);
};

Alternatively, you can use ES6 modules for the same purpose.

(In my app, I am using a private Meteor package that establishes the app object and exports it to the global namespace. In this case, you don’t have to prefix it with window.)

2 Likes

Omitting var adds the variable to the global namespace?