Why is the variable not defined?

I have the following function:

$.getJSON( 'getTerminalinsideCircle.json', { centerLatitude: adressMarker.getPosition().lat(), centerLongitude:adressMarker.getPosition().lng(), radius :radius/1000 }, function (data) { $.each(data, function (key, val) { .... } ) } ) 

I needed to reorganize it and rewrite it like this:

 $.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 the console I see that Uncaught ReferenceError: data is not defined

How to reorganize it?

+5
source share
1 answer

Use renderTerminalOnMap instead of renderTerminalOnMap(data) as a callback.

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

When you pass functions as callbacks, you just need to pass the function name, the parameters will be passed to 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) { ... } ) } 
+9
source

Source: https://habr.com/ru/post/1204477/


All Articles