When we linked require.js
to our application, we told it to use main.js
as our entry point. To test that this works, let's start by entering a dummy main.js
. JavaScript files in Play applications go in /public/javascripts
:
// public/javascripts/main.js require([], function() { console.log("hello, JavaScript"); });
To verify that this worked, head to 127.0.0.1:9000
and open the browser console. You should see "hello, JavaScript"
in the console.
Let's now write a more useful main.js
. We will start by configuring RequireJS, giving it the location of modules we will use in our application. Unfortunately, NVD3, the graph library that we use, does not play very well with RequireJS so we have to use an ugly hack to make it work. This complicates our main.js
file somewhat:
// public/javascripts/main.js (function (requirejs) { 'use strict'; // -- RequireJS config -- requirejs.config({ // path to the web jars. These definitions allow us // to use "jquery", rather than "../lib/jquery/jquery", // when defining module dependencies. paths: { "jquery": "../lib/jquery/jquery", "underscore": "../lib/underscorejs/underscore", "d3": "../lib/d3js/d3", "nvd3": "../lib/nvd3/nv.d3", "bootstrap": "../lib/bootstrap/js/bootstrap" }, shim: { // hack to get nvd3 to work with requirejs. // see this so question: // http://stackoverflow.com/questions/13157704/how-to-integrate-d3-with-require-js#comment32647365_13171592 nvd3: { deps: ["d3.global"], exports: "nv" }, bootstrap : { deps :['jquery'] } } }) ; })(requirejs) ; // hack to get nvd3 to work with requirejs. // see this so question on Stack Overflow: // http://stackoverflow.com/questions/13157704/how-to-integrate-d3-with-require-js#comment32647365_13171592 define("d3.global", ["d3"], function(d3global) { d3 = d3global; }); require([], function() { // Our application console.log("hello, JavaScript"); }) ;
Now that we have the configuration in place, we can dig into the JavaScript part of the application.