【问题标题】:WinJS variable is changed only inside functionWinJS 变量仅在函数内部更改
【发布时间】:2016-12-02 10:35:34
【问题描述】:

我在 WinJS 中的变量范围存在问题。当变量改变时,它应该在更大的范围内可见,但在调用函数之后,这个变量只有在函数内部才有值。我认为这是 readTextAsync 的问题,因为当我在没有 readTextAsync 的函数中填充变量时,它正在工作。

这是变量声明:

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");
        });
    }

附:对不起我的英语不好。它并不完美:)

【问题讨论】:

    标签: javascript variables scope uwp winjs


    【解决方案1】:

    我认为这是 readTextAsync 的问题,因为当我在没有 readTextAsync 的函数中填充变量时,它正在工作。

    我从您上一篇文章的代码中得出了这个答案。Windows.Storage.FileIO.readTextAsync 是一个 Windows 异步 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");
                });
            }
    

    【讨论】:

    • 它还活着!我必须更改代码中的某些内容,但是您的解决方案非常有帮助。谢谢。
    猜你喜欢
    • 2013-03-14
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2021-03-16
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多