12

After hours of search, I Have a problem with my code Below. In fact, I'm not very far from answer I think but I'm still blocked…</p>

I have an anonymous function called inside a loop and I want to access and refresh global variables but I tried with window.myvariable, with another function and nothing happen…</p>

this my code :

for (var i = 0; i < SHP_files.length; i++) {
            shapefile = new Shapefile({
                shp: "shp/polygon/"+SHP_files[i]+".shp",
                dbf: "shp/polygon/"+SHP_files[i]+".dbf",
                }, function(data) {

                    polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
                    polygon_layer.addTo(map);
                    console.log(polygon_layer.getLayers()); // IS OK
                });
        };
        console.log(polygon_layer.getLayers()); // IS EMPTY !!

So, How i could transform this anonymous function in order to have something that I can access from my code who's following that ?

Thanks a lot, and sorry for my english not very good…</p>

4

2 回答 2

5

这是异步代码执行的典型问题。您的示例代码不会从上到下执行。特别是,您的匿名函数在Shapefile完成它正在做的任何事情之前都不会被执行。同时,您的 JS 会按顺序执行。因此,上述代码的最后一行可能会在匿名函数之前执行。

要解决此问题,您需要触发任何依赖Shapefile于其回调中响应的代码:

for (var i = 0; i < SHP_files.length; i++) {
    shapefile = new Shapefile({
        shp: "shp/polygon/"+SHP_files[i]+".shp",
        dbf: "shp/polygon/"+SHP_files[i]+".dbf",
        }, function(data) {
            polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
            polygon_layer.addTo(map);
            executeMoreCode();
        });
};

function executeMoreCode() {
    console.log(polygon_layer.getLayers()); // IS OK
}
于 2013-10-03T20:42:45.847 回答
2

尝试在 for 循环或函数之外定义变量,在本例中为 polygon_layer。请参见以下示例:

var f;
for(var i=0; i<5;i++){
    (function(){
        f = 10;
        console.log(f); // Outputs 10
    })();
}
console.log(f); // Also outputs 10
于 2013-10-03T20:40:21.440 回答