Search code examples
javascriptobject-literal

Javascript: pass var to object literal


I'm having a problem with this code:

$(function () {
    $('#city_input').autocomplete({
        onSelect: function (suggestion) {
            alert(suggestion.data);
            window.latlng = suggestion.data;
        }
    });

    $('#fs_input').autocomplete({
        params: { "latlng" : window.latlng, "latlng2" : '99.9999,-99.9999' },       
        onSelect: function (suggestion) {
            alert(window.latlng);
        }       
    });
});

This is an autocomplete script. First the user selects a suggestion on #city_input. Doing that, it sets the value for window.latlng.

Then next, the user needs to select a suggestion on #fs_input. The problem I'm having is that, in the "params" property, the "latlng" : window.latlng property is not being set. Just for tests, I also created another property, seen in the code, latlng2 which is working fine. Also, a little below, I'm doing an alert(window.latlng) to check the value and it alerts the expected value.

So the question is, why "latlng" : window.latlng is not being set? Maybe I'm not supposed to pass a variable to an object liberal property?


Solution

  • It is being set. It's simply that it has no value at the point when you're setting it.

    The value isn't computed dynamically after #city_input's onSelect callback fires, it's being computed once when the script first loads, long before you ever assign to it.

    $('#city_input').autocomplete({
        onSelect: function (suggestion) {
            alert(suggestion.data);
            # you assign here, in a callback that executes some time after the page loads
            window.latlng = suggestion.data;
        }
    });
    
    $('#fs_input').autocomplete({
        # however, you *read* the value here, immediately on page load, long before `onSelect` ever runs
        # window.latlng is "undefined" at the point `params` is created.
        params: { "latlng" : window.latlng, "latlng2" : '99.9999,-99.9999' },       
        onSelect: function (suggestion) {
            alert(window.latlng);
        }
    
    });
    

    If you want a value selected in the onSelect callback to be used in the autocomplete for a different element, you need to wait to initialize the autocomplete until after a value is selected and actually available:

    $('#city_input').autocomplete({
        onSelect: function (suggestion) {
            alert(suggestion.data);
            window.latlng = suggestion.data;
    
            $('#fs_input').autocomplete({
                params: { "latlng" : window.latlng, "latlng2" : '99.9999,-99.9999' },       
                onSelect: function (suggestion) {
                    alert(window.latlng);
                }
            });
        }
    });