RequireJS - 将参数传递给模块进行初始化 [英] RequireJS - pass parameters into module for initialization

查看:258
本文介绍了RequireJS - 将参数传递给模块进行初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

我目前正在为我们的某个项目创建一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆