Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS - pass parameters into module for initialization [duplicate]

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?

like image 942
Christian Engel Avatar asked Apr 25 '12 15:04

Christian Engel


3 Answers

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

like image 50
ggozad Avatar answered Sep 28 '22 11:09

ggozad


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

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

like image 38
dlrust Avatar answered Sep 28 '22 10:09

dlrust


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:

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

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:

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.

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.

like image 28
Christian Engel Avatar answered Sep 28 '22 09:09

Christian Engel