RequireJS - pass parameters into module for initialization

Christian Engel picture Christian Engel · Apr 25, 2012 · Viewed 29.8k times · Source

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?

Answer

ggozad picture ggozad · Apr 25, 2012

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