我想通过我正在收听的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应用程序?
答案 0 :(得分:3)
可以在我的主模块中添加事件监听器。 因此应用程序会被主模块的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 :)
}
});
答案 1 :(得分:1)
这种方法的问题在于污染了它 全局命名空间,它过于复杂。为什么不只是要求 设备准备回拨中的应用程序?
<body>
<script>
function onDeviceReady() {
require(['app'], function(App) {
app.init()
}
}
</script>
</body>
然后你甚至不需要main.js! (除非你想添加一些 配置)。
答案 2 :(得分:0)
另一种解决方案是使用承诺:
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();
});
});