Question

I have been studying John Papa's pluralsight course on SPA.

In his main.js, he gave a name to each js library which is included in the bundle.

(function () {
var root = this;

define3rdPartyModules();


function define3rdPartyModules() {
    // These are already loaded via bundles. 
    // We define them and put them in the root object.
    define('jquery', [], function () { return root.jQuery; });
    define('ko', [], function () { return root.ko; });
    define('amplify', [], function () { return root.amplify; });
    define('infuser', [], function () { return root.infuser; });
    define('moment', [], function () { return root.moment; });
    define('sammy', [], function () { return root.Sammy; });
    define('toastr', [], function () { return root.toastr; });
    define('underscore', [], function () { return root._; });
}

})();

But what is the root here?


By doing so, we can call those short names in the define statement:

define('vm.session',
['ko', 'datacontext', 'config', 'router', 'messenger', 'sort'],
function (ko, datacontext, config, router, messenger, sort) {

Current, I don't know how to do that. So my working define statement is ugly:

define('vm.admin.outfitters',
['/Scripts/lib/jquery-1.8.1.js', '/Scripts/lib/jsrender.js', ...], function(){...

I know there's gotta be a better way. All those js files have been included in the script bundle already. How can I reference those scripts?

Was it helpful?

Solution

RE: root

RequireJS and the AMD ready libraries remove the objects from the global scope (things like ko). Some plugins want them in global scope, so we can either shim those plugins or pop the objects back in global scope. The latter is what is happening in this code. It's being done for the plugins for Knockout primarily.

RE: your define statements

The first parameter is the name of of the module, so you are fine there. THe second parameter is the list of modules that RequireJS is aware of. The 3rd parameter is the matching variable to represent it. So in your code you might have something like this ...

define('vm.admin.outfitters',
['jquery', 'jsrender'], function($, jsrender) { 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top