Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does variable is not defined?

I have following function:

    $.getJSON(
                    'getTerminalinsideCircle.json',
                    {
                        centerLatitude: adressMarker.getPosition().lat(),
                        centerLongitude:adressMarker.getPosition().lng(),
                        radius :radius/1000

                    }, function (data) {
                          $.each(data, function (key, val) {
                                   ....
                          }
                        )
                    }
            )

I wanted ro refactor it and rewrite it so:

$.getJSON(
                'getTerminalinsideCircle.json',
                {
                    centerLatitude: adressMarker.getPosition().lat(),
                    centerLongitude: adressMarker.getPosition().lng(),
                    radius: radius / 1000

                }, renderTerminalOnMap(data)
        )
        function renderTerminalOnMap(data) {
            $.each(data, function (key, val) {
                       ...
                    }
            )
        }

but in console I see that Uncaught ReferenceError: data is not defined

How to refactor it right?

like image 681
gstackoverflow Avatar asked Oct 11 '14 15:10

gstackoverflow


1 Answers

Use renderTerminalOnMap instead of renderTerminalOnMap(data) as callback.

By writing renderTerminalOnMap(data) you actually immediately call the function with the data parameter, which is an undefined variable, and set the return value of that function as the callback.

When you pass functions as callbacks you just have to pass the function name, the parameters will be transmitted by the getJSON function itself.

        $.getJSON(
                'getTerminalinsideCircle.json',
                {
                    centerLatitude: adressMarker.getPosition().lat(),
                    centerLongitude: adressMarker.getPosition().lng(),
                    radius: radius / 1000

                }, renderTerminalOnMap
        );

        function renderTerminalOnMap(data) {
            $.each(data, function (key, val) {
                       ...
                    }
            )
        }
like image 169
XCS Avatar answered Oct 17 '22 06:10

XCS