[GIS] How to use onLayerAddResult in the ArcGIS Server JavaScript API

arcgis-javascript-api

The JS API help file shows how to listen for the onLayerAddResult event.

onLayerAddResult(layer, error)

Fires after specified layer has been added to the map

I can't get it to work reliably. Using this sample, and adding the following line:

dojo.connect(map, "onLayerAddResult", operationalLayer,  function(){alert("test")});

results in the alert appearing 3 times. What am I doing wrong?

(Note that there is a separate onLayersAddResult (plural) event but I'm interesting in knowing when the first layer (only) has been added.)

Best Answer

The event fires every time a layer is added, not just the first time. In that sample, three different layers are added. You need to disconnect your connect after it is fired the first time if you only want to know when the first layer has been added. To do this, you need to assign your connect to a variable to keep reference to it and then disconnect using that reference.

var connectFirstLayerAdd = dojo.connect(map, "onLayerAddResult", this, function(){
     dojo.disconnect(connectFirstLayerAdd);
     alert("test");
});

Also, the third argument is a scoping argument for running the function. I suspect you would not want to use operationalLayer as your scope. I scope it to this because I need connectFirstLayerAdd to be in the scope of the connected function, otherwise it will not be able to successfully execute the call to dojo.disconnect.

If you do need to scope the function to operationalLayer then instead you need to assign your connect to a property of operationalLayer

operationalLayer.connectFirstLayerAdd = dojo.connect(map, "onLayerAddResult", operationalLayer, function(){
     dojo.disconnect(connectFirstLayerAdd);
     alert("test");
});