Select to view content in your preferred language

How can I use a variable that is set in a function on an on event outside of the event?

4208
10
09-02-2015 04:57 AM
MichaelStranovsky
Occasional Contributor

For instance:

featureLayer.on("selection-complete", function (result){

        var pPoly = result.features[0].geometry;

});

console.log(pPoly);

the console returns undefined

0 Kudos
10 Replies
ReneRubalcava
Frequent Contributor II

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.