alex.mironov
alex.mironov

Reputation: 2942

How to avoid global variables in Durandal 2

As I know Durandal 2.x assumes no global libraries. Here is the code snipped to define global modules from documentation:

define('jquery', function () { return jQuery; });
define('knockout', function () { return ko; });

If I understand the purpose correct, these dependencies should be used within modules in the next way:

define(['jquery', 'ko'],
    function (jquery, ko) {
         debugger;
    });

But neither of these dependencies (jquery, ko) are defined in scope of the module. Could you please help me to figure out what am I missing here?

Upvotes: 0

Views: 756

Answers (1)

RainerAtSpirit
RainerAtSpirit

Reputation: 3723

There are two ways to get knockout and jQuery (and other third party libs) loaded in Durandal.

Via script tags

<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/knockout-2.3.0.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.js"></script>

e.g. see Microsoft .NET samples https://github.com/BlueSpire/Durandal/blob/master/platforms/Microsoft.NET/Samples/Durandal.Samples/Views/Home/Index.cshtml#L31

In that case you'd use the above syntax to make requirejs aware that those libraries are already loaded, because Durandal interaly uses them as AMD modules. In your own modules however you can omit this declariation as 'ko' and '$' are globally accessible.

For some people this is the pragmatic way as it's easier to deal with third party libs that are not AMD compatible.

If avoiding globals is top priority than requirejs can be configured that way as well.

Load everything via requierejs. Only one script tag required

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

e.g. see HTML samples https://github.com/BlueSpire/Durandal/blob/master/platforms/HTML/Samples/index.html#L43

In main.js there's a requirejs.config object with path and shim configuration. See http://requirejs.org/docs/api.html for a full set of available option.

main.js

requirejs.config({
    paths: {
        'text': '../lib/require/text',
        'durandal':'../lib/durandal/js',
        'plugins' : '../lib/durandal/js/plugins',
        'transitions' : '../lib/durandal/js/transitions',
        'knockout': '../lib/knockout/knockout-2.3.0',
        'bootstrap': '../lib/bootstrap/js/bootstrap',
        'jquery': '../lib/jquery/jquery-1.9.1'
    },
    shim: {
        'bootstrap': {
            deps: ['jquery'],
            exports: 'jQuery'
        }
    }
});

e.g. https://github.com/BlueSpire/Durandal/blob/master/platforms/HTML/Samples/app/main.js

This time within your own modules you have to declare 'knockout' and 'jquery' as dependency (if you use them) otherwise requirejs will throw an error.

Upvotes: 1

Related Questions