簡體   English   中英

從隨附的JS文件訪問全局變量

[英]Accessing global Variables from included JS-File

我想從包含的JS文件訪問全局變量。 是的,我知道,我不是第一個遇到此問題的人,但是這里的答案對我沒有任何幫助。 我在代碼中寫了一些注釋來描述我的問題。

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-文件中設置了值后,我無法訪問OBJECT3D.lengthProduct01。 請,我需要一些幫助! 這已經花了我很多時間! :(

謝謝!

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);

此示例無法正常工作,因為等待限制太小,並且適當的值(不是太小又不是太高)取決於連接。 您可以使用10000ms或類似的東西進行測試,它幾乎總是可以工作,但是時間太長。

更好的解決方案是使用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

所以這是我的解決方案,對我有用:

/*
     *  ####################################################
        *  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;
    }

希望這對其他有同樣問題的人有所幫助! ;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM