Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't RequireJS passing jQuery into the functions alias?

I downloaded the sample-project for the latest-release of RequireJS. Their documentation implies anything loaded is passed-into the parameter list of the associated function (in corresponding order).

So I decided to try it...but it doesn't seem to work!

  • Firebug (net tab) shows jQuery as being loaded: so RequireJS obvioulsy did that part successfully
  • Firebug (console tab) shows '$ is not a function'

My question is: Why isn't the alias getting populated?

MY CODE LOOKS LIKE:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="Scripts/require.js" type="text/javascript"></script>

    <script type="text/javascript">

        require(["scripts/jQuery/Core/jquery-1.7.2.min"], function ($) {

            // jQuery is not passed-into the function, so the alias fails!
            $(function () {
                var stop = "";
            });
        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

THIER SAMPLE LOOKS LIKE:

//Inside scripts/main.js
require(["some/module", "a.js", "b.js"], function(someModule) {
    //...
});
like image 698
Prisoner ZERO Avatar asked Apr 12 '12 20:04

Prisoner ZERO


1 Answers

jQuery should be loaded through the special name "jquery", otherwise it won't register itself (since jQuery uses a named define).

// create an alias that points to proper file
require.config({
  paths : {
    jquery : "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min"
  }
});

// require jquery usign the path config
require(["jquery"], function ($) {
    console.log($);
});

That is the main reasons why named define is considered an anti-pattern and should be used only when needed (when you have multiple modules inside same file).

like image 149
Miller Medeiros Avatar answered Oct 14 '22 16:10

Miller Medeiros