Callback before RequireJS “define” function is cal

2019-07-22 00:11发布

问题:

I'm new to Backbone, and i'm helping to maintain an app that has lots of Backbone and RequireJS code that does something like so:

define(

    ['backbone', 'underscore'],

    function(Backbone, _) {
      // some code here
    }
);

I'd like to configure Underscore in each of these pages... In the most simple sense, I could just do something like so:

define(

    ['backbone', 'underscore'],

    function(Backbone, _) {

      // do some stuff to configure underscore
      configureUnderscore(_);

    }
);

but I'd like to leave each page's define function alone, and just inject a callback that's called before the define callback is called.

How can this be done with Backbone or RequireJS?

回答1:

The simplest would probably to define a requireJS module named (e.g.) rawUnderscore which returns Undercore without any configuration.

Then, create a new module named underscorewhich requires rawUnderscore and configures it before returning its value.



回答2:

Here's how to make this work as suggested in another answer on this page, and copied from this StackOverflow answer to a similar question:

main.js

requirejs.config({
    paths: {
        'underscore': 'underscoreConfig',
        'originalUnderscore': 'underscore'
    },
    shim: {
        'originalUnderscore': {
            exports: '_'
        }
    }
});

underscoreConfig.js

define(['originalUnderscore'], function(_) {
    _.templateSettings =
    {
        evaluate    : /<%([\s\S]+?)%>/g,
        interpolate : /<%cleanHtml([\s\S]+?)%>/g,
        escape      : /<%[=-]([\s\S]+?)%>/g
    };
    return _;
});


回答3:

Another approach (completely untested) may be to define a "require" variable before require.js is included, as detailed here in the Require.JS docs, and here as well

<script>
    var require = {
        deps: ["some/module1", "my/module2", "a.js", "b.js"],
        callback: function(module1, module2) {
            //This function will be called when all the dependencies
            //listed above in deps are loaded. Note that this
            //function could be called before the page is loaded.
            //This callback is optional.
        }
    };
</script>
<script src="scripts/require.js"></script>