RequireJS - pass parameters into module for initia

2020-06-11 12:20发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
How to load bootstrapped models in Backbone.js while using AMD (require.js)

I am currently creating a RESTful API for one of our projects and also wanted to provide a Javascript library to access it.

Since I like the AMD principle and using require.js, I would provide an AMD module as well. The problem is: the initialization of the module would require some information like the API key on initialization.

How do I pass such parameters into a module upon initalization?

回答1:

If you have something like:

define(['dep1', 'dep2', 'dep3'], function (dep1, dep2, dep3) {

    var module = {
        ...
    };

    return module;

});

change it to:

define(['dep1', 'dep2', 'dep3'], function (dep1, dep2, dep3) {
    var module = {
        ...
    };

    var init = function (options) {
        // Initialize here
        return module;

    };

    return init;
});

Then after requiring your module somewhere, you can call it to initialize. You might also want to look into the factory pattern if you need something more complex and return the factory.

require.js does not restrict you in what you return. It can be a simple object, a string, a function...



回答2:

I think what your looking for is the ability to set config variables that get picked up by the module. Here is an example using require.js

How to load bootstrapped models in Backbone.js while using AMD (require.js)



回答3:

One other possibility that came to my mind is to use a serverside script to manipulate the source of the module when you are requesting it.

For example when you have to pass an API-key into the module, you do the following:

Before you do your first define() call, put the following code:

require.config({
    paths: {
        api: 'https://api.example.com/api.amd.js?api_key=f615ac61&'
    }
});

This enables you to simply require your API from anywhere like this:

require(['api'], function(api){

});

So the server recieves the request - maps it thorugh mod_rewrite to some script, takes the GET parameter and puts it on the correct place in the module sourcecode, then returns the custom source.

Thats the way I solved this by now and it works like a charm, without the need to change any behaviour of the developers and it makes use of functionality thats already built into requirejs.



回答4:

I don't think you can do that with require.js, but you can with Frame.js or some other module library. In Frame you would do that like this:

//moduleName.js

(function(exports){
    exports.moduleName = function(args){
        // do stuff
    }
})(window.exports);


// in main js file

var exports = {}; // global variable

Frame('moduleName.js');
Frame(function(next){
    var myArgs = { ... settings ... };
    exports.moduleName(myArgs);
    next();
});
Frame.init();


回答5:

Is it possible to use a namespaced variable, and then to reference the appropriate object when you initialize the specific library? Maybe I don't understand exactly what you want require.js to do, but it looks like you call it from your main.js in any event, so I'm pretty sure it would work... I don't think you can do it like <script = "require.js?apiKey=jsdfhjkfklsjkfdjks">

var libData = {
   apiKey: "jsdfhjkfklsjkfdjks",
   otherpram: "userIDorsomething"
}

require(libData.apiKey); 

but if you needed to send the apikey in the url parameter of the page, you could use a script like this to get the parameters:

<script>
      function getQueryParams(qs) {
            qs = qs.split("+").join(" ");
            var params = {},
                tokens,
                re = /[?&]?([^=]+)=([^&]*)/g;

            while (tokens = re.exec(qs)) {
                params[decodeURIComponent(tokens[1])]
                    = decodeURIComponent(tokens[2]);
            }

            return params;
        }

// assuming the page is loaded like page.html?apikey=jsdfhjkfklsjkfdjks

     apiKey = getQueryParams(document.location.search).apiKey;

// however you have to call require, pass the api key?

</script>