且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-10 16:11:04

如果你有类似的话:

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