开发者

Javascript anonymous function not updating global variable

I've got a $.getJSON call in some code that appear to be not updating a global variable, and I'm at a loss to understand why. The JSON data is being loaded OK, but for some reason the global EventOptions array is not being updated in the for {} loop. The capitalised comments refer to the variable. Any ideas? Thanks

function LoadMeasurementTypes() {
    // Clear out EventOptions
    EventOptions = ["..."];
    // Push a couple on to EventOptions - THESE ADD OK
    EventOptions.push("Temperature");
    EventOptions.push("Pulse rate");
    // Call json to get measurementTypes off the table    
   开发者_StackOverflow中文版 $.getJSON('./get-measurement-types.php', function (measurementTypeData) {
        // Process each json element ([0].BP, [1].ph (Urine) etc.
        for (var i = 0; i < measurementTypeData.length; ++i) {
            // e is a storage variable to contain the current element
            var e = measurementTypeData[i];
            // Add the new measurement type
            alert(e.measure_type); // OK works - we can see the measure_type
            EventOptions.push(e.measure_type); // THESE ARE NOT BEING ADDED 
        }
    } // end anonymous function
    ) // end get json call
    EventOptions.push("Last one"); // THIS ONE IS BEING ADDED
}


Your EventOptions[] is not globally visible. My guess would of been that it should still be visible locally to your $.getJSON call; but because it is now scoped to jquery, its clearly obscured (did you alert(EventOptions); inside your anon function to test?.

To properly scope, just declare it outside of LoadMeasureTypes().

var EventOptions = ["..."];
function LoadMeasureTypes(){...

-update

if this does not work - you could always pull the anonymous function outside of the $.getJSON() and assign it a variable name:

var retreiveTypes = function(){...};

$.getJSON("..path/php", retreiveTypes);


window.EventOptions = ["..."]

Good 'ol "hack" to put stuff in the global context


Got the answer: well kind of. It won't work on iTouch Safari, but is fine on Firefox (Mac). Bosworth I'm figuring it's a browser issue you noted above. Interestingly, it may be something to do with threads. It appear the out loop runs before the inner anonymous loop has finished (the alerts are not in sequence!). I didn't think javascript used threads this way, but I may be wrong.

I now suspect the whole issue is a timing one - with a new thread as an anonymous function not completing in time.

Thanks guys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜