How to set global variables in Javascript/HTML5 in Windows8 store app

前端 未结 4 444
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 19:34

I want to use global variable in .js files. For example,

when I read a file content in \" a.js + a.html \" and saved into a certain variable \'fileContent\'

相关标签:
4条回答
  • 2020-12-21 20:09

    Use localStorage.
    In A:

    localStorage.setItem('fileContent', 'value;');
    

    In B:

    var fileContent = localStorage.getItem('fileContent');
    

    Or just access the localStorage like any other object:

    localStorage.fileContent = "value";
    

    However, keep in mind that the localStorage converts all values to strings, this includes objects and array. To set / get those, you'll need to use JSON.stringify and JSON.parse, respectively:

    localStorage.setItem('fileContent', JSON.stringify([1,2,3,4,5,6,7]));
    var fileContent = JSON.parse(localStorage.getItem('fileContent'));
    
    0 讨论(0)
  • 2020-12-21 20:14

    You can easily define a variable and can use it as a global variable,for example

    WinJS.Namespace.define("MyGlobals", {i: 0,k:5    })
    

    For checking you can add an event listener like

    div1.addEventListener('click', divClickEvent);
    
    function divClickEvent() {
            MyGlobals.i++;
            MyGlobals.k++;
            console.log("ValueOf_i____" + MyGlobals.i);
            console.log("ValueOf_k____" + MyGlobals.k);
        }
    
    0 讨论(0)
  • 2020-12-21 20:15

    You can also use App Settings:

    var applicationData = Windows.Storage.ApplicationData.current;
    var localSettings = applicationData.localSettings;
    var composite = new Windows.Storage.ApplicationDataCompositeValue();
    composite["intVal"] = 1;
    composite["strVal"] = "string";
    
    localSettings.values["exampleCompositeSetting"] = composite;
    

    Here You can find more information: Link

    0 讨论(0)
  • 2020-12-21 20:22

    Given that the architecture for Windows 8 Applications is the single page model, where you don't navigate the browser, but merely load a fragment of HTML and insert it into the current document, this is very easy. I would, however, recommend using some typing, rather than just a "naked" global variable.

    File A (globals.js):

    WinJS.Namespace.define("MyGlobals",  {
        variableA: null,
    });
    

    Include this at the top of default.html after the WinJS includes.

    File B (b.js):

    // your other code
    ...
    MyGlobals.variableA = getValueFromSomewhere();
    

    File C (b.html, or c.js):

    // your other code
    ...
    printSomethingAwesomeFromData(MyGlobals.variableA);
    
    0 讨论(0)
提交回复
热议问题