【问题标题】:initializing phonegap by deviceready event using require.js使用 require.js 通过 deviceready 事件初始化 phonegap
【发布时间】:2014-01-21 09:57:35
【问题描述】:

我想找到一种方法,通过我正在监听的 deviceready 事件来初始化我的应用程序。

我要加载这个 javascript 文件:

//index.html
<head>
    <script src="cordova.js">
    <script src="require.js" data-main="main.js">
</head>

现在我想在设备真正准备好之后调用 main.js 的一个函数来开始初始化我的应用程序。但我没有任何访问权限,因为它是一个 requirejs 模块。

//index.html
<body>
    <script>
         function onDeviceReady() {
              //main.js initialize my app
         }
    </script>
</body>

能够像这样在 main.js 中调用函数真是太好了:

//main.js
var myApp = {};
define(['app'],
    function(app){
       var init = function(){
             app.run();
        }
        myApp.init = init;
    }
);

比我的 index.html 还早:

<body>
    <script>
         function onDeviceReady() {
             myApp.init();
         }
    </script>
 </body>

我不知道这是否可行。 你如何使用 requirejs 初始化你的 phonegap 应用程序?

【问题讨论】:

    标签: cordova requirejs


    【解决方案1】:

    事件监听器可以添加到我的主模块中。 所以应用程序被主模块的 deviceready 事件初始化,如下所示:

    require([
    'config/RootPathConfig',
    'app',
    'overrides'
    ], function(rootPath, app){
    
        document.addEventListener("deviceready",onDeviceReady,false);
    
        function onDeviceReady() {
            console.log("deviceReady");
            rootPath.initialize();
            app.init();                         //now the app content is loaded after the device is ready :)
        }
    
    });
    

    【讨论】:

      【解决方案2】:

      这种方法的问题是它污染了 全局命名空间,而且过于复杂。为什么不只是要求 设备就绪回调中的应用程序?

      <body>
          <script>
               function onDeviceReady() {
                 require(['app'], function(App) {
                   app.init()
                 } 
               }
          </script>
      </body>
      

      那么你甚至不需要 main.js! (除非你想添加一些 配置)。

      【讨论】:

      • 我想问题是 require.js 需要一个模块作为 xyz.js 作为引用来应用。因此,由于这里的关系,我需要 main.js(模块):
      • data-main 属性是可选的。欢迎您使用它并将配置信息放在文件 main.js 中,但仅限于需要时。
      • 所以我可以留空吗?我明天试试。到目前为止 thx 很多。
      • 不幸的是,将
      【解决方案3】:

      另一种解决方案是使用承诺:

      onDeviceReady.js

      define(function() {
        return new Promise(function(resolve, reject) {    
          if (document.URL.match(/^https?:/i)) { // credits to http://stackoverflow.com/a/12255930/1225328
            console.log("Running in a browser...");
            resolve();
          } else {
            console.log("Running in an app...");
            document.addEventListener("deviceready", resolve, false);
          }
        });
      });
      

      main.js

      define(["onDeviceReady", "app"], function(onDeviceReady, app) {
        onDeviceReady.then(function() {
          // device is ready, bootstrap your app:
          app.run();
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-05
        • 2012-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多