【问题标题】:How should I organise code so that I can see instances of a class in multiple pages of a WinJS Store App?我应该如何组织代码,以便我可以在 WinJS Store App 的多个页面中看到类的实例?
【发布时间】:2014-11-26 16:52:56
【问题描述】:

(示例取自http://msdn.microsoft.com/en-us/library/windows/apps/hh967793.aspx

如果我在主页上的 default.js 文件之后存储了机器人类。

// robot.js
(function () {
     var Robot = WinJS.Class.define(function (name) {
            this.name = name;
        },
        { modelName: "" },
        { harmsHumans: false, obeysOrders: true }
    );

    WinJS.Namespace.define("Robotics", {
        Robot: Robot
    });
})();

在 page1.js 中,我创建了一个机器人实例。

// page1.js
var myRobot = new Robotics.Robot("Sam");
var harm = Robotics.Robot.harmsHumans;

从 page2.js 访问 myRobot 实例的最佳方式是什么?

// page2.js
console.log(myRobot.name);

我查看了 WinJS 命名空间,但我看到的所有示例都显示从同一页面访问的实例。

我是否应该将实例存储在某种存储中?

【问题讨论】:

    标签: javascript windows-store-apps winjs


    【解决方案1】:

    WinJS 命名空间只是将命名空间名称(例如 Robotics)作为变量添加到全局命名空间中,因此您放置在命名空间中的任何内容(例如 Robotics.Robot)都可以从代码中的任何其他位置从该根名称访问。这意味着您可以在robot.js 中的命名空间定义中添加另一个成员,例如robotInstance: null,然后在page1.js 中设置Robotics.robotInstance = myRobot; . page2.js 然后就可以访问 Robotics.robotInstance,没问题。

    底线是 WinJS 命名空间只是保持全局命名空间组织和整洁的约定,否则它只是全局变量。没有魔法。

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      相关资源
      最近更新 更多