iwan
iwan

Reputation: 7569

Unable to load crossroads.js using RequireJS

I try to load JS files using RequireJS , however crossroads http://millermedeiros.github.io/crossroads.js/ seems not be loaded properly. I have checked using Chrome Dev Toolbar and all JS files are actually loaded. However running window.crossroad returned me undefined?

Below is my requirejs config.. Kindly advice... Thanks!

index.html

<script data-main="scripts/config" src="scripts/require.js"></script>

config.js

require.config({
  shim: {
    "zepto.min": {
      exports: "$"
    },
    "underscore.min": {
      exports: "_"
    },
    "crossroads.min": {
      exports: "crossroads"
    }  }
});

require(["zepto.min","underscore.min", "crossroads.min",], function() {
    console.log("=> Loading app")
    require(["main"]);
});

main.js

require(["hp-config", "hp-model", "hp-view", "hp-controller"], function () {
    console.log("=> Init");
    console.log(window.crossroads);
    //$(document).ready( function(){ HP.C.init(); });
});

Upvotes: 0

Views: 383

Answers (1)

Louis
Louis

Reputation: 151411

If you look at the code for crossroads, you'll see that it detects that it is in a AMD environment (which RequireJS is) and calls define by itself. So you should remove the shim you have for it. The basic rule is: a library that does not call define needs a shim but a library that calls define does not. The reason window.crossroads is undefined is that crossroads calls define instead of exporting itself in the global space (on window).

Given the require.config call you currently have, the updated call would be:

require.config({
  shim: {
    "zepto.min": {
      exports: "$"
    },
    "underscore.min": {
      exports: "_"
    }
  }
});

The above config is the minimum change required. However, I would also advise not using .min in the names you pass to require or define. So your config.js could be instead:

require.config({
  paths: {
    zepto: "zepto.min",
    underscore: "underscore.min",
    crossroads: "crossroads.min"
  },
  shim: {
    zepto: {
      exports: "$"
    },
    underscore: {
      exports: "_"
    }
  }
});

require(["zepto","underscore", "crossroads",], function() {
    console.log("=> Loading app")
    require(["main"]);
});

This way, if you want to switch to the non-minified version (for debugging) you can just change the paths setting instead of having to go everywhere you require these modules and change the names.

Upvotes: 0

Related Questions