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?
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) {
...
}
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With