Eddie Rowe
Eddie Rowe

Reputation: 168

global variable shows in console as undefined - didn't used to

This comes as the first javascript declaration in my module:

<script type='text/javascript'>
var json_meets;
var teams;
var my_meet;

window.onload = function() {
    AJAX( '/ajax/getFacilities.html','','populate_datalist_from_array','facilities' );
    AJAX( '/ajax/getAssociations.html','','process_associations','datalist_for_new_team_Association' );
$( "#add_team_dialog" ).dialog({ autoOpen: false });
    window.json_meets = { "meets" : [] };
    window.teams = [];
    window.my_meet = {
        "meet_name" : "",
        "meet_date" : "",
        "meet_id"   : "",
        "meet_location" : "",
        "teams"     : []
    };
}

later on I include a file or two that declares this function:

function submitTeamToAdd( obj ) {
var doit = 0;

// get Display name of team in input box
var team = document.getElementById( 'add_team_input' ).value;

for ( var i = 0 ; i < window.my_meet.teams.length ; i++ ) {
    if ( getTeamDisplayName( window.my_meet.teams[i] ) == team ) {
        alert( team + ' is already participating.' );
        document.getElementById( 'add_team_input' ).value = '';
        return;
    } 
}   

for ( var i = 0 ; i < window.teams.length ; i++ ) {
    if ( getTeamDisplayName( window.teams[i] ) == team ) {
        doit = 1;
        break;
    }   
}
if ( doit == 1 ) {
    putTeamOnList( team , obj );
} else {
    // open the dialog to add a new team to the database
    openDialog( 'add_team_dialog' );

    // pass thru the name of the team that was entered clear out legacies.
    document.getElementById( 'add_new_team_Name' ).value = team;
    document.getElementById( 'add_new_team_Nickname' ).value = '';
    document.getElementById( 'add_new_team_Association' ).value = '';
    document.getElementById( 'add_new_team_Mascot' ).value = '';
    document.getElementById( 'add_new_team_Classification' ).value = '';
}
}

When that function fires, the console throws:

TypeError: window.my_meet is undefined

How is it undefined? The variables are declares and initialized inside the window.onload function. I can understand that they're essentially empty, but that doesn't make them undefined, right? It should just be an array of length 0.

Upvotes: 0

Views: 120

Answers (2)

nico
nico

Reputation: 835

Try using window['my_meet'] everywhere rather than window.my_meet

Upvotes: 0

Blender
Blender

Reputation: 298046

It's undefined because you didn't define it. You declared it, but it still has a value of undefined at the time your function attempts to access it.

window.onload fires after all of your resources (including images) have loaded, but you seem to call your function before that happens. You need to wait for the AJAX calls to finish before calling your functions.

Upvotes: 2

Related Questions