How To Set Global Variables In Javascript/html5 In Windows8 Store App
Solution 1:
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);
Solution 2:
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
Solution 3:
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);
functiondivClickEvent() {
MyGlobals.i++;
MyGlobals.k++;
console.log("ValueOf_i____" + MyGlobals.i);
console.log("ValueOf_k____" + MyGlobals.k);
}
Solution 4:
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'));
Post a Comment for "How To Set Global Variables In Javascript/html5 In Windows8 Store App"