For instance:
featureLayer.on("selection-complete", function (result){
var pPoly = result.features[0].geometry;
});
console.log(pPoly);
the console returns undefined
Michael,
That when you use lang.hitch to maintain the scope of the function:
Be sure to require dojo/_base/lang
featureLayer.on("selection-complete", lang.hitch(this,function (result){ var pPoly = result.features[0].geometry; //Now to will have access to the external var inside this function })); console.log(pPoly);
Hi Robert,
Thanks for the quick response but I actually want to access the pPoly variable outside the onEvent after the function has been executed.
Michael
You can define the variable outside your function , but just so you know the console.log will still return undefined since it will run before your selection. To test you would have to put the console.log into your other "on" function.
var pPoly; featureLayer.on("selection-complete", function (result){ pPoly = result.features[0].geometry; }); console.log(pPoly);
Well think of it the same way now that you have access to the outside scope of the function you just set an outside var that you create to the pPoly.
var pPoly; featureLayer.on("selection-complete", lang.hitch(this,function (result){ pPoly = result.features[0].geometry; //Now to will have access to the external var inside this function })); console.log(pPoly);
Yeah I tried that and the console still reports undefined but if I place the console.log inside the event it return correctly. I need to use it though outside the event.
You are having scope and order of execution issues.
To do what you want, you need to do something like this.
var pPoly; function saySomething() { console.log(pPoly); } featureLayer.on("selection-complete", function (result) { pPoly = result.features[0].geometry; saySomething(); });
dojo/on does not return a Promise, so you cannot use then with it.
I'd recommend you look over this blog post
Take your JavaScript Up a Notch
And in particular look at closures.
Aangemelde leden kunnen berichten plaatsen, updates volgen en meer. Nieuw hier? Registreer een gratis account.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.