2

I'm trying to get more in line w/ AMD, and I've come across something in jQuery source that I just can't quite undertand.

Here is section (found just before the end of the file):

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
    define( "jquery", [], function () { return jQuery; } );
}

From what I can see, one of the major points of AMD is to keep the global scope clean. Yet jQuery chooses to return a reference to itself as a module, but still infects the global space.

It seems to me, that adding "jQuery.noConflict();" just before the return would resolve this and still return the object as a module.

I know that RequireJS has some special files specifically for jQuery, but I'm not sure that it's needed for 1.7+.

My question is 2 part:

1) Does anyone know why this decision was taken?

2) Since this approach is not upgrade friendly, is anyone familiar with a more elegant solution that utilizes the standard version of RequireJS and jQuery?

Just a guy
  • 5,812
  • 4
  • 21
  • 25
  • http://stackoverflow.com/questions/4858431/use-requirejs-and-jquery-without-clobbering-global-jquery/9593868#9593868 – Matt S Mar 07 '12 at 00:14

1 Answers1

3

Ok, just after posting, I just realized I could proxy it through another file:

//main.js
require.config({
    paths : {
    jquery : 'my/libs/jquery-1.7.1.min',
    jQuery : 'my/src/jquery'
}

and

//my/src/jquery.js

define([
        'jquery'
    ],
    function($) {
        $.noConflict(true);

        return $;
    }
);

The reason for the 'jquery' alias for the main file rather than just reference the fully qualified location in the proxy is because I'm using an AMD-ready branch of Backbone that depends on this alias:

https://github.com/jrburke/backbone/blob/2b0cfb4282f071cffb14a9573d703da6acc5febd/backbone.js

The author has had some commits accepted by Document Cloud and is hoping that this modification gets drawn in too.

It will be interesting to see if there are any flaws with this or what additional answers there could be from the AMD battle tested.

Just a guy
  • 5,812
  • 4
  • 21
  • 25
  • How are you dealing with jQuery plugins with this setup? I think the reason they left $ in the global scope was so their library of plugins (their biggest strength) that aren't built for AMD would still work. – nicholas Mar 30 '12 at 18:56
  • 1
    Is there no way to make the $ local and still use plugins? – ThomasReggi Mar 22 '13 at 16:14
  • Have you taken a look at [shim support for non-AMD libraries](http://requirejs.org/docs/api.html#config-shim)? That wasn't available back when this question was originally posted. So perhaps this feature will do it. However, I haven't tested it. – Just a guy Mar 25 '13 at 16:46