从包含的JS-File访问全局变量

时间:2014-02-04 14:38:16

标签: javascript global-variables

我想从包含的JS-File访问全局变量。是的,我看到,我不是第一个遇到这个问题的人,但这里的答案中没有任何内容适合我。我在我的代码中写了一些评论来描述我的问题。

main.js

var drawing_area;
var renderer;
var camera;
var tableTop;
var scene;

var OBJECT3D = {}; // the global namespace

var texture_path = "/images/materials/texture_1.jpg";
var texture;


$(function() {

    // get the product-identifier via URL
    OBJECT3D.productIdentifier = document.URL.split('/').pop();


    // get all default values from select-elements and store them in a global hash
    OBJECT3D.defaultValues = {};
    $('select').each(function() {
        var selectedOption = $(this).find('option:selected');
        OBJECT3D.defaultValues[$(this).data('identifier')] = selectedOption.text();
    });


    /*
     *  ####################################################
        *  SET ALL DEFAULT VALUES DEPENDING ON THE PRODUCT *
     *  ####################################################
     *  
     *  import custom js-code via <script> - Tag   
     *
     */
    var script_values_setter   = document.createElement("script");
    script_values_setter.type  = "text/javascript";


    switch (OBJECT3D.productIdentifier) {

        case "product_01":
            script_values_setter.src   = "/javascripts/3D_models/default_values_setters/product_01.js"; // include js-File
            document.body.appendChild(script_values_setter); // append it to the DOM

            break;
        // ...
        default:
            break;
    }

// try to access the length, which i set in product_01.js, but it's undefined, so i can't use it
console.log("length-value: "+OBJECT3D.lengthProduct01);

// ... some other stuff for what i need the values of the product_01.js - File



});

product_01.js

// in here i can access the global variable OBJECT3D.defaultValues without any problems ...
$.each(OBJECT3D.defaultValues, function(key, value) {
        switch (key) {
            case "laenge":
                // here i set the length in a global var
                OBJECT3D.lengthProduct01 = value.replace(/[A-Za-z$-]/g, "")*10; 
                break;
            case "breite":
                OBJECT3D.widthProduct01 = value.replace(/[A-Za-z$-]/g, "")*10;
                break;
            default:
                break;
        }
    });

所以问题是我在设置product_01.js - File中的值后无法访问OBJECT3D.lengthProduct01。拜托,我需要一些帮助!这花了我很多时间! :(

谢谢!

2 个答案:

答案 0 :(得分:1)

JavaScript是单线程环境。当您执行document.body.appendChild(script_values_setter);脚本添加到DOM时,但在当前脚本结束之前不会处理。 然后,当您的程序到达OBJECT3D.lengthProduct01行时,未设置该值。您必须先结束脚本,然后再花一些时间访问另一个脚本,然后才能访问OBJECT3D.lengthProduct01属性。你应该尝试这样的事情:

// invoke function later (in 1ms)
// During the wait phase JS engine will grant a processor time to another scripts (timer functions, callbacks for events, etc.)
window.setTimeout(function() {
    // try to access the length, which i set in product_01.js - this should works
    console.log("length-value: "+OBJECT3D.lengthProduct01);

    // ... some other stuff for what i need the values of the product_01.js - File
}, 1);

此示例无法正常工作,因为等待限制太小而且正确的值(不是太小而不是太高)取决于连接。你可以测试10000毫秒或类似的东西,它几乎总能工作,但它太长了。

更好的解决方案是使用jQuery函数getScript而不是setTimeout。

    ...
    switch (OBJECT3D.productIdentifier) {
        case "product_01":
            // append js-File to the DOM
            $.getScript("/javascripts/3D_models/default_values_setters/product_01.js", function() {
                // try to access the length, which i set in product_01.js - this should works
                console.log("length-value: "+OBJECT3D.lengthProduct01);

                // ... some other stuff for what i need the values of the product_01.js - File
            });
            break;
        // ...
        default:
            break;
    }
    // nothing here - the code is moved to getScript callback function
});

以下是我的工作示例http://ulozto.net/xSprWGU8/load-script-zip

答案 1 :(得分:1)

所以这是我的解决方案,对我有用:

/*
     *  ####################################################
        *  SET ALL DEFAULT VALUES DEPENDING ON THE PRODUCT *
     *  ####################################################
     *
     */

    function setJsScript(path, callback) {
        var script                = document.createElement('script');
        script.type               = 'text/javascript';
        script.src                = path;
        script.onreadystatechange = callback;
        script.onload             = callback;
        document.getElementsByTagName('body')[0].appendChild(script);
    }


    switch (OBJECT3D.productIdentifier) {
        case "product_01":

            setJsScript('/javascripts/3D_models/default_values_setters/product_01.js', function(){
                console.log("-> length-value: "+OBJECT3D.lengthTableTop); // now i cann access the var :)
                // some other stuff ...
            });

            break;
        default:
            break;
    }

希望这可以帮助其他人解决同样的问题! ; - )