Saturday, March 7, 2015

Problem when assigning value to a variable defined outside of a function

I wrote this code:

searchBtnIsEnabled: {value: function(){
    var isEnabled;
    this.searchBtn.isEnabled().then(function(result){
      isEnabled = result;
      console.log("the isEnabled is: "+isEnabled);
    });
    console.log(isEnabled);
  }}


But the logged isEnabled is undefined. Then I change it to:

searchBtnIsEnabled: {value: function(callback){
    this.searchBtn.isEnabled().then(function(result){
      callback(result);
    })
  }}

this.searchBtnIsEnabled(function(enable){
    console.log("The enable is: "+enable);
})

Then it works.

REASON : Javascript Asynchronous

Please read:
http://tech.pro/blog/1402/five-patterns-to-help-you-tame-asynchronous-javascript
http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron

No comments:

Post a Comment