Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CommonJS - How can I combine jquery and a jquery-plugin into the $ namespace

What I'm trying to do is adapt my jQuery-plugin to work with jQuery on Node.js.

From what I understand, CommonJS in it's most basic form requires a library to be wrapped in a closure, and that closure should be made available as a parameter of an 'exports' parameter. That way, the code is neatly contained in its own namespace (via a named variable) and doesn't pollute the global namespace.

jQuery itself should fall under the '$' namespace.

Ala:

var $ = require(jquery);

But my plugin should also fit under the '$' namespace.

Plugin code:

(function( $ ) {
  // plugin code goes here
})(jquery);

exports.jquery = jquery // will this work?

Ex:

var $ = require(jquery);
$ = require(jquery-csv.js); // will this work?

To work in the browser, everything is setup to be callable from the '$' namespace even though my modules are setup as a sub-namespace of '$' (ie '$.csv').

Is there a standard way to do multiple requires on a single namespace? If not, there a viable alternative (ex doing a shallow copy on the plugin code)?

Note: The anonymous function wrapper follows the standard jquery guidelines.

Note: This fix will be applied to the jquery-csv plugin.

like image 319
Evan Plaice Avatar asked Oct 03 '12 21:10

Evan Plaice


2 Answers

You should require jQuery inside your plugin:

var $ = require("jquery");

This is also the technique in UMD (Universal Module Definition), a standard for both CommonJS and AMD.

Also see the example for a jQuery plugin with UMD

like image 162
squarebrackets Avatar answered Oct 03 '22 09:10

squarebrackets


Easiest way I can think of doing something like this would be doing something like the following:

var $ = require("jquery");
require("jquery-csv")($);

That also means you can just do something like this:

module.exports = exports = function (jquery) {
    //You modify the jquery object here.
};

Modification of the $ object should be done in accordance to jQuery plugins recommendations. I will believe you are already aware of them for what you said.

I'm sure someone will come up with a smarter way :) but this should work for now. You could also just return a modified jquery object and then assign it to the $ object on the scope in which you originally included the module.

like image 44
Mamsaac Avatar answered Oct 03 '22 10:10

Mamsaac