Pergunta

I wrote a JavaScript module loader which defines different modules within a loop..

function(moduleList) {
    var arr = [];
    for (i = 0, l = moduleList.length; i < l; i++) {
        var m = moduleList[i];

        define(m.guid, function() {
            return  {
                container : m.container,
                configuration : m.configuration,
                moduleId : m.id
            }
        });
        arr[i] = m;
    }
}

Directly after that there is the next for loop in which I "require" the previously defined modules..

for (i = 0, l = arr.length; i < l; i++) {   
   require([arr[i].id,arr[i].guid], function(module, moduleConfiguration) {
        core.utils.log("m.id: " + moduleConfiguration.moduleId);
        core.utils.log("init " + moduleConfiguration.moduleId, moduleConfiguration);

        module.init(moduleConfiguration);
    });
}

The problem now is that inside every "require" block the moduleConfiguration and module is the same.. To make a "require" call it uses different ids but the result is always the same.

Does somebody know how to find a way arround this?

Foi útil?

Solução

I think your definition function should look like this, so that "m" is properly scoped:

function(moduleList) {
    var arr = [], i; // declare i!!!!
    function def(m) {
        define(m.guid, function() {
            return  {
                container : m.container,
                configuration : m.configuration,
                moduleId : m.id
            }
        });
    }

    for (i = 0, l = moduleList.length; i < l; i++) {

        var m = moduleList[i];

        def(m);
        arr[i] = m;
    }
 }

In your code, the same variable "m" is shared among all those module callbacks. By introducing another function (and another scope), you make sure that each callback has its own copy.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top