I have the below code which ensures a layer is valid before adding it to the map. mapConfig.Services is an array of service url's and loadMapService is a simple function which returns an ESRI layer. The layer is added once it is "loaded" using an index (defined in mapConfig.Services). This works fine for two layers because no matter what order the event onLoad fires, they come in they will be normalised (0 will end up at position 0 regardless of if 1 was added before it). My problem is that I think that these could be different servers in different locations firing the onLoad event with varying speeds.
For example, if I had 5 layers and by chance the onLoad event fired in the order 4,3,2,1,0 they would remain in that order since the index would always be greater than the number of layers and therefore append to the end (the objective is to order them 0,1,2,3,4).
I could use map.reorderLayer() to compare back to the original array, however, how will I know once all of the layers have been loaded? map.onLoad fires after the first layer is added so I can't do it here. Also assume that some of the layers could be missing and will not fire onLoad (I have connected to the onError event). I don't really want to check the layer order after a maximum timeout period.
Maybe there is something really obvious I'm missing?
for (var i = 0; i < mapConfig.Services.length; i++) {
layer[i] = this.loadMapService(mapConfig.Services[i], true);
if (layer[i] != null) {
//In Internet Explorer, due to resource caching, the onLoad event is fired as soon as the layer is constructed. Consequently you should check whether the layer's loaded property is true before registering a listener for the onLoad event:
//http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/arcgis/help/jshelp_start.htm#jshelp/inside_events.htm
if (layer[i].loaded) {
this.map.addLayer(layer[i]);
}
else {
layer[i].index = i;
dojo.connect(layer[i], "onLoad", dojo.hitch(this, function (addlayer) {
var self = this;
self.map.addLayer(addlayer, addlayer.index);
}));
}
}
};