slhck
slhck

Reputation: 38691

Why is my closure variable cleared after using $.each on JSON data?

Consider the following example:

var features = [];

$.getJSON(annotations_url, function(data) { 
  $.each(data, function(key, val) {
    features.push(wkt_parser.read(val.annotation.wkt_data));
    // at this point, "features" contains objects
  });
});

annotationLayer.addFeatures(features);
// here, it is empty again

Here, I expect features to continuously grow. However, in the last line, features is empty again.

Why is that and how would I correctly push values to features from within the $.each (or rather the anonymous function inside)?

Upvotes: 3

Views: 93

Answers (2)

robyaw
robyaw

Reputation: 2311

This is to do with the asynchronous behaviour of the $.getJSON function. Move annotationLayer.addFeatures(features); inside the $.getJSON function.

The features variable isn't being "cleared"; rather, it has not being populated when annotationLayer.addFeatures(features); is executed.

Upvotes: 1

Alex
Alex

Reputation: 9471

The $.getJSON call is asynchronous, so annotationLayer.addFeatures is probably being executed before the JSON request has finished. Call the addFeatures method inside the $.getJSON call, after the .each loop.

If you need to perform more stuff with features, consider creating a new function (which includes the addFeatures method you need to call), and then call this new function after the .each loop inside the $.getJSON call.

Upvotes: 5

Related Questions