locked
Can't access a variable outside a function in a javascript

    Question

  • Hi All,

    I am having the following code in a .js file. The issue that I am facing is that i am not able access the updated value of variable "alarmDataArray" in the function "createNameSpace".

    I think the problem is with the scope of variable but I am not able to debug it.

    (function () {

        "use strict";

        var applicationData = Windows.Storage.ApplicationData.current;
        var localFolder = applicationData.localFolder;
        var alarms = [];
        var a;
        var oneAlarmInfo;
        var alarmDataArray;

        localFolder.createFolderAsync("AlarmData", Windows.Storage.CreationCollisionOption.openIfExists).then(function (dataFolder) {
            dataFolder.getFileAsync("AlarmsInfo.txt").then(function (dataFile) {
                return Windows.Storage.FileIO.readTextAsync(dataFile).then(function (dataFileText) {
                    dataFileText = dataFileText.substr(1, dataFileText.length);
                    alarms = dataFileText.split(";");
                    a = dataFileText;
                    console.log("1" + a);
                    alarmDataArray = [];
                    for (var i = 0; i < alarms.length; i++) {
                        var ala = alarms[0].split("_");
                        oneAlarmInfo = {
                            name: ala[0],
                            type: ala[1],
                            date: ala[2] + "-" + ala[3] + "-" + ala[4]
                        }
                        alarmDataArray.push(oneAlarmInfo);
                    }
                    createNameSpace(alarmDataArray);
                }).done(function () { console.log("2" + alarmDataArray[0].date); });
            },
             function error(e) {
         }).done();
        }).done();

        function createNameSpace(alarmDataArray) {
            console.log("3" + a);
            console.log(alarmDataArray[0].date);
            var dataList = new WinJS.Binding.List(alarmDataArray);
            var publicMembers =
            {
            itemList: dataList
            }
            WinJS.Namespace.define("DataExample", publicMembers);
        }
        //console.log("ravi" + DataExample.itemList.getAt(0).date);
    })();

    Monday, May 28, 2012 4:28 PM

Answers

  • Try putting it in front/before your main "(function () {" block.

    We had to do that in our code for some reason...it's been a few months so forgot why. Example below, and we use the bannerDataSource inside the code everywhere...

    Example of our code:

    var bannerDataSource = new WinJS.Binding.List([]);

    (function () {
      'use strict';

    • Marked as answer by ravipiplani Monday, May 28, 2012 5:16 PM
    • Unmarked as answer by ravipiplani Monday, May 28, 2012 5:17 PM
    • Marked as answer by ravipiplani Monday, May 28, 2012 5:17 PM
    Monday, May 28, 2012 4:50 PM