jgillich
jgillich

Reputation: 76249

Require.js with jQueryMobile-Router

I load require.js with jQuery included like this in my html:

<script data-main="requires" src="lib/require-jquery.js"></script>

The content of my requires.js:

require.config( {
      paths: {
            "jquery.mobile": "lib/jquery.mobile",
            "jquery.mobile.router": "lib/jquery.mobile.router"

      },
      shim: {
            "jquery.mobile" : {
                "exports": "$.mobile"
            },
            "jquery.mobile.router": {
                  "deps": [ "jquery.mobile" ],
                  "exports": "$.mobile.Router"
            }

      }

} );

require(["jquery.mobile.router" ], function() {
    require(["router"]);
} );

And in my router.js i create a new instance of the jquery mobile router plugin:

router = new $.mobile.Router(...);

Which gives me this error:

Uncaught TypeError: undefined is not a function

When I output $ and $.mobile, they are both defined, just $.mobile.Router is undefined.

What have I done wrong here?

Upvotes: 1

Views: 635

Answers (2)

jgillich
jgillich

Reputation: 76249

My Problem was that I added jquery.mobile as a dependency for jquery.mobile.router, thus jQuery mobile will be loaded first, where as the documentation for the router states this:

The jQuery Mobile router javascript file must be loaded before jQuery Mobile.

This is how I changed my requires.js to fix the problem:

require.config( {

    paths: {
        "jquery.mobile": "lib/jquery.mobile",
        "jquery.mobile.router": "lib/jquery.mobile.router"
    },

    shim: {
        "router": {
            "deps" : ["jquery.mobile"]
        },
        "jquery.mobile" : {
            "deps" : [ "jquery.mobile.router"],
            "exports": "$.mobile" 
        },

        "jquery.mobile.router": {
          "exports": "$.mobile.Router"
        }
    }
});

require(["router"]);

Now I just require my router.js and load jquery.mobile and jquery.mobile.router as dependencies. Load order now is this:

  1. jquery.mobile.router
  2. jquery.mobile
  3. router

Upvotes: 2

Calvin Cheng
Calvin Cheng

Reputation: 36516

Try this in your router.js file:-

define(["jquery", "jquery.mobile.router"], function($) {
    // your js code in router.js
} );

By specifying jquery in your define call and passing in $ as an argument, the jquery object $ and associated functions defined in jquery.mobile.router are now made available in the scope of your code (contained in the file router.js in its entirety).

Upvotes: 1

Related Questions