Louis
Louis

Reputation: 2608

jquery global variables usable everywhere

I am starting to doubt that jquery is easy to use and flexible. I have this:

var prodata=[];
var request = $.get("proDB.txt", function(data) {
    var lines=data.split(/\n/);
    var numberofmodels=lines.length-2;
    //var prodata=[];
    var i;
    prodata.push(0);
    var fieldnames=lines[0].split(/\t/);
    for (i = 1; i < lines.length-1; ++i) {
        var fields=lines[i].split(/\t/);
        prodata.push(i);            
        var j;
        prodata[i]={};
        for (j = 0; j < fields.length; ++j) {
            //prodata[i][fieldnames[j]]=fields[j];
            var str=fieldnames[j];
            prodata[i][str]=fields[j];

        }
    }

    //FILL THE DROPDOWN LIST
    var options = '';
    for (i = 1; i < lines.length-1; ++i) {
        if (prodata[i]['name'].indexOf("elly") >= 0) {
            var iselected = i;
        }
        options += '<option label="bla" value="' + prodata[i]['id'] + '">' + prodata[i]['name']+', '+prodata[i]['brand']+', '+prodata[i]['model']+'</option>';
    }
    $("#userchosenpromodel").html(options);
    //SELECT DEFAULT OPTION
    $('#userchosenpromodel option[value="' + prodata[iselected]['id'] + '"]').attr("selected", "selected");
}, 'text'); //$.get

I would like to use proId, lower in my code, after it's been defined like that:

//SUBMIT FORM
$('#submitbutton').click(function(e) {
    e.preventDefault(); 
    request.done(function(){
        proId=$('#userchosenpromodel option[selected="selected"]').val();
        proId=parseInt(proId);
        computeUserDimensions(prodata[proId]);
    });
});
    console.log(proId);

How to?

Same problem for prodata...I have request.done that I can't get rid of

Thanks

Upvotes: 0

Views: 129

Answers (2)

Leeish
Leeish

Reputation: 5213

Why not do:

request.done(function(){
    proId=$('#userchosenpromodel option[selected="selected"]').val();
    doSomethingWithProId();
});

function doSomethingWithProId(){
    console.log(proId);
}

OR so it doesn't need to be a Global

request.done(function(){
    var proId=$('#userchosenpromodel option[selected="selected"]').val();
    doSomethingWithProId(proId);
});

function doSomethingWithProId(proId){
    console.log(proId);
}

The second solution in my mind is better. Whatever you need to do with proId build your functions to pass in that data. That way you don't need to pollute the global scope. Sounds like you need a better understanding of JS.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

You don't have a problem with jQuery but with asynchronous/event based logic.

You can't synchronously use the return of an asynchronous function. You must use the result in the callback or in a function you call from the callback :

request.done(function(){
    var proId=$('#userchosenpromodel option[selected="selected"]').val();
    console.log(proId);
});

Upvotes: 4

Related Questions