0

I'm creating a new FeatureLayer, and I want to populate the popup with a list of all the fields. Here is part of my code:

var featureLayer = new FeatureLayer(url, {
    mode: FeatureLayer.MODE_ONDEMAND,
    outFields:["*"],
    infoTemplate: popupTemplate
});
var fieldArray1 = featureLayer.fields;
console.log(fieldArray1); // output: undefined

// But, this gives me what I want:
setTimeout(function(){
    var fieldArray2 = featureLayer.fields;
    console.log(fieldArray2); //output: an array of Field Objects
},5000);

I believe one of my problems is that I don't fully how to handle the fact that javascript is asynchronous. I realize that var fieldArray1 = featureLayer.fields; is executing before the FeatureLayer Object finished being created.

What is the correct and best way to code what I want to do, which is - "after the new FeatureLayer Object is created, set fieldArray1 = featureLayer.fields?"

1

Reading the docs : https://developers.arcgis.com/javascript/3/jsapi/featurelayer.html#event-load

In JavaScript if code is asynchronous, should be provided an event / callback function that fires once the code is done. It seems there's a load event. So, try something like this :

featureLayer.on('load', function(response){
  console.log(response.layer.fields);
});
  • 1
    The response Object looks like this: {layer: Object, target: Object}. So, this works: ...function(response){console.log(response.layer.fields);});. Thanks for the help! – skihansen May 17 '16 at 1:25
  • Uuups! Just a mistake, I have never used ArcGIS JavaScript API. I'll update my anwser. ;P – Jose Hermosilla Rodrigo May 17 '16 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.