Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  11] [ 3]  / answers: 1 / hits: 21271  / 8 Years ago, fri, april 8, 2016, 12:00:00

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 I did:



I installed both packages from npm like so:



npm install jquery
npm install jsdom


then I required them in my node.js app:



require(jsdom).env(, function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require(jquery)(window);
});
doSomething();


Then I'm trying to use it like so:



function doSomething(){
var deferred = $.Deferred();
}


and I get the following error:



var deferred = $.Deferred();
^
ReferenceError: $ is not defined


Do you think that the function is getting executed before the var $ = part?



Thanks!



Versions:




  • Node: 4.2.6

  • Express: 4.12.4

  • JQuery: 2.2.3

  • JSDom: 8.3.0



Update: Solution



Here's what I ended up using, based on everyone's answers!



var $;
require(jsdom).env(, function(err, window) {
if (err) {
console.error(err);
return;
}
$ = require(jquery)(window);
doSomething();
});

More From » jquery

 Answers
6

Your doSomething function is declared outside if the bounds of the jsdom.env function. $ is only accessible inside that callback. Something like this should work:



var $;

require(jsdom).env(, function(err, window) {
if (err) {
console.error(err);
return;
}
$ = require(jquery)(window);
doSomething();
});

function doSomething(){
var deferred = $.Deferred();
}


Though I think it would be more idiomatic to just declare doSomething inside the callback. That way it would have access to jquery from the outer scope.



require(jsdom).env(, function(err, window) {
if (err) {
console.error(err);
return;
}

function doSomething(){
var deferred = $.Deferred();
}
var $ = require(jquery)(window);
doSomething();
});

[#62644] Wednesday, April 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;