Question

I'm refactoring a javascript codebase and am implementing, but I'm new to node. I might run into some code like this:

foo.js

var foo = {};
foo.bar = function(baz) {
    $('body').append(baz)
}

which i would then refactor into the following:

foo.js

var $ = require('jquery')(window);
var foo = {};
foo.bar = require('./bar');

bar.js

module.exports = bar = function(baz) {
    $('body').append(baz);
}

What's the correct way to pass the jQuery object from foo.js to bar.js without interfering with the baz parameter when foo.bar(baz) is called?

Was it helpful?

Solution

Just add var $ = require('jquery')(window) to each module that needs jQuery!

Calls to require that resolve to the same path will return a cached copy of the module:

http://nodejs.org/api/modules.html#modules_caching

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top