我想找到一种通过我正在听的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初始化电话盖应用程序?
可以在我的主模块中添加事件侦听器。因此,该应用程序由这样的主模块的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 :)
}
});
这种讨论的问题是它污染了全球名称空间,它过于复杂。为什么不需要设备中的应用已准备好回调?
<body>
<script>
function onDeviceReady() {
require(['app'], function(App) {
app.init()
}
}
</script>
</body>
那么您甚至不需要main.js!(除非您想添加一些配置)。
另一个解决方案是使用承诺:
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();
});
});