2016-07-28 19 views
1

WinJSでは変数スコープに問題があります。変数が変更されると、より大きなスコープで表示されるはずですが、コール関数の後では、この変数は関数内にのみ値を持ちます。私はreadTextAsyncに問題があると思います。なぜなら、readTextAsyncのない関数で変数を埋めると、それが働いているからです。WinJS変数は関数内でのみ変更されます

これは、変数の宣言です:

var fileDate; 

これは私が別の呼び出し機能である:

WinJS.UI.Pages.define("index.html", { 
     ready: function (element, options) { 
      loadDate(); 
      console.log("główna " + fileDate); //fileDate = undefined 
      this.fillYearSelect(); 
     }, 

そして、これは、変数が変更された関数で、次のとおりです。

localFolder.getFileAsync(filename).then(function (file) { 
       Windows.Storage.FileIO.readTextAsync(file).done(function (fileContent) { 
       fileDate = fileContent; // example - fileDate=a073z160415 
       console.log("fileDate " + fileDate); 
      }, 
      function (error) { 
       console.log("Reading error"); 
      }); 
     }, 
     function (error) { 
      console.log("File not found"); 
     }); 
    } 

P.S.私の英語には申し訳ありません。完全ではありません:)

答えて

1

私はreadTextAsyncを使わない関数で変数を埋めると、それが働いているので、readTextAsyncに問題があると思います。

最後の投稿のコードからこの回答を作成しました。 Windows.Storage.FileIO.readTextAsyncは、ウィンドウ非同期APIです。したがって、非同期の方法で処理する必要があります。console.log("główna " + fileDate)loadDate().then()で処理し、fileContentを返す必要があります。これはloadDate().then(function(data){})で捕捉できます。

WinJS.UI.Pages.define("index.html", { 
    ready: function (element, options) { 
     loadDate().then(function(data){ 
      fileDate=data; //here catch the fileContent data 
      console.log("główna " + fileDate); 
     }); 
     this.fillYearSelect(); 
    }, 

function loadDate() { 
      var that = this; 
      var filename = "abc.txt"; 
      return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(filename).then(function (file) { 
       return Windows.Storage.FileIO.readTextAsync(file).then(function (fileContent) { 
        return fileContent;//here return the fileContent.You can catch it outside. 
       }, 
       function (error) { 
        console.log("Błąd odczytu"); 
       }); 
      }, 
      function (error) { 
       console.log("Nie znaleziono pliku"); 
      }); 
     } 
+0

これは生きている!私はコード内で何かを変更しなければなりませんが、あなたのソリューションは非常に役に立ちます。ありがとうございました。 –

関連する問題