RequireJS - 将参数传递给模块进行初始化 [英] RequireJS - pass parameters into module for initialization
问题描述
我目前正在为我们的某个项目创建一个RESTful API,并且还想提供一个Javascript库来访问它。
I am currently creating a RESTful API for one of our projects and also wanted to provide a Javascript library to access it.
由于我喜欢AMD原理并使用require.js,我也会提供AMD模块。
问题是:初始化模块需要一些信息,比如初始化时的API密钥。
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?
推荐答案
如果你有类似的话:
define(['dep1', 'dep2', 'dep3'], function (dep1, dep2, dep3) {
var module = {
...
};
return module;
});
将其更改为:
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不会限制您返回的内容。它可以是一个简单的对象,一个字符串,一个函数......
require.js does not restrict you in what you return. It can be a simple object, a string, a function...
这篇关于RequireJS - 将参数传递给模块进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!