如何在 Windows8 商店应用程序的 Javascript/HTML5 中设置全局变量

2022-01-21 00:00:00 windows-8 javascript

我想在 .js 文件中使用全局变量.例如,

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

当我读取a.js + a.html"中的文件内容并保存到某个变量fileContent"中时

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

那么我也想在b.js + b.html"中使用那个'fileContent'.

then I also want to use that 'fileContent' in " b.js + b.html ".

(另外,当我更改b.js + b.html"中的fileContent"时,应该会影响a.js + a.html"中的fileContent")

(also, when I change the 'fileContent' in "b.js + b.html", that should affect 'fileContent' in "a.js + a.html")

我该怎么办?

谢谢.

推荐答案

鉴于 Windows 8 应用程序的架构是单页模型,您无需浏览浏览器,而只需加载 HTML 片段并插入它进入 current 文档,这很容易.但是,我建议使用一些类型,而不仅仅是裸"全局变量.

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.

文件 A (globals.js):

File A (globals.js):

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

在 WinJS 包含之后,将其包含在 default.html 的顶部.

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

文件 B (b.js):

File B (b.js):

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

文件 C(b.html 或 c.js):

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

// your other code
...
printSomethingAwesomeFromData(MyGlobals.variableA);

相关文章