Javascript RequireJS - 将参数传递给模块进行初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10319027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:50:08  来源:igfitidea点击:

RequireJS - pass parameters into module for initialization

javascriptmodulerequirejsamd

提问by Christian Engel

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

可能的重复:
如何在使用 AMD (require.js) 时在 Backbone.js 中加载引导模型

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

我目前正在为我们的一个项目创建一个 RESTful API,并且还想提供一个 Javascript 库来访问它。

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.

因为我喜欢 AMD 原理并使用 require.js,所以我也会提供一个 AMD 模块。问题是:模块的初始化需要一些信息,比如初始化时的 API 密钥。

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

如何在初始化时将这些参数传递给模块?

回答by ggozad

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 callit 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...

require.js 不会限制您返回的内容。它可以是一个简单的对象、一个字符串、一个函数......

回答by dlrust

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

我认为您要寻找的是能够设置模块获取的配置变量。这是一个使用 require.js 的示例

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

使用 AMD (require.js) 时如何在 Backbone.js 中加载引导模型

回答by Christian Engel

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:

例如,当您必须将 API 密钥传递到模块中时,您可以执行以下操作:

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

在您第一次调用define() 之前,输入以下代码:

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:

这使您可以像这样从任何地方简单地要求您的 API:

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.

因此,服务器收到请求 - 通过 mod_rewrite 将其映射到某个脚本,获取 GET 参数并将其放在模块源代码中的正确位置,然后返回自定义源。

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.

这就是我现在解决这个问题的方式,它就像一个魅力,不需要改变开发人员的任何行为,它利用了 requirejs 中已经内置的功能。

回答by BishopZ

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

我不认为你可以用 require.js 做到这一点,但你可以用Frame.js或其他一些模块库。在 Frame 中,你会这样做:

//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();

回答by Peter Hanley

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">

是否可以使用命名空间变量,然后在初始化特定库时引用适当的对象?也许我不明白你想要 require.js 做什么,但看起来你在任何情况下都从你的 main.js 调用它,所以我很确定它会工作......我不认为你可以这样做 <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:

但是如果你需要在页面的 url 参数中发送 apikey,你可以使用这样的脚本来获取参数:

<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?

// 但是你必须调用 require,传递 api 密钥?

</script>