Help! I\'m trying to use jquery in my node.js app, but I keep getting an error when I try to use \'$\', saying \"$ is not defined\"... but I defined it at the top! Here\'s what
All you need to do is to move the call doSomething() inside your callback function right after $ initialization.
// define global variable for further usage
var $;
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
// initialize global variable
$ = require("jquery")(window);
// will work properly here
doSomething();
});
function doSomething() {
// using already initialized global variable
var deferred = $.Deferred();
}
In your example there are 2 things you need to take care:
1. Asynchronous functions
We need to guarantee doSomething will be called only after $ initialization.
2. Variable scopes
It really makes sense what is the place you declared doSomething function and in your example doSomething doesn't know $ exists at all. So we need to define it somewhere (e.g. globally) to make a closure with $ variable.