我正在创建我的第一个Cordova项目,我是JavaScript新手。
我正在学习一些教程,但现在我正在将一些JavaScript代码集成到index.js文件中。
在Joerg回答后编辑了index.js:
// Declaraci—n de variables globales
var myScroll, myScrollMenu, cuerpo, menuprincipal, wrapper, estado;
console.log('ENTRANDO!!!!');
// Guardamos en variables elementos para poder rescatarlos despuŽs sin tener que volver a buscarlos
cuerpo = document.getElementById("cuerpo"),
menuprincipal = document.getElementById("menuprincipal"),
wrapper = document.getElementById("wrapper");
var xhReq = new XMLHttpRequest();
var app = {
// Constructor de la app
initialize: function() {
console.log('ENTRANDO EN VAR APP FUNCTION()!!!');
// Estado inicial mostrando capa cuerpo
estado="cuerpo";
// Creamos el elemento style, lo a–adimos al html y creamos la clase cssClass para aplicarsela al contenedor wrapper
var heightCuerpo=window.innerHeight-46;
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { position:absolute; z-index:2; left:0; top:46px; width:100%; height: '+heightCuerpo+'px; overflow:auto;}';
document.getElementsByTagName('head')[0].appendChild(style);
// A–adimos las clases necesarias
cuerpo.className = 'page center';
menuprincipal.className = 'page center';
wrapper.className = 'cssClass';
// Leemos por ajax el archivos opcion1.html de la carpeta opciones
xhReq.open("GET", "opciones/opcion1.html", false);
xhReq.send(null);
document.getElementById("contenidoCuerpo").innerHTML=xhReq.responseText;
// Leemos por ajax el archivos menu.html de la carpeta opciones
xhReq.open("GET", "opciones/menu.html", false);
xhReq.send(null);
document.getElementById("contenidoMenu").innerHTML=xhReq.responseText;
// Creamos los 2 scroll mediante el plugin iscroll, uno para el menœ principal y otro para el cuerpo
myScroll = new iScroll('wrapper', { hideScrollbar: true });
myScrollMenu = new iScroll('wrapperMenu', { hideScrollbar: true });
this.bindEvents();
},
bindEvents: function() {
$(document).ready(function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
});
},
onDeviceReady: function() {
// Ejecutamos la funci—n FastClick, que es la que nos elimina esos 300ms de espera al hacer click
new FastClick(document.body);
console.log('ENTRANDO EN VAR ONDEVICEREADY!!!');
app.readPosts();
},
readPosts: function() {
posts_url: "http://your.ip.goes.here:3000/posts/";
console.log('Reading posts');
$.ajax({
type: "GET",
dataType: "json",
url: app.posts_url,
success: app.onSuccess,
error: app.onError
});
console.log('Reading posts asynchrounously');
},
onSuccess: function(data) {
var items = [];
$.each(data, function(key, val){
items.push('<a href="' + app.posts_url + val.id + '">' + val.id + ' - ' +val.title + '</a>');
});
$('#posts').html(items.join('<br/>'));
console.log('Exiting onSuccess');
},
onError: function(data, textStatus, errorThrown) {
console.log('Data: ' + data);
console.log('Status: ' + textStatus);
console.log('Error: ' + errorThrown);
$("#posts").html('Error while loading posts');
console.log('Exiting onError');
}
};
// Funci—n para a–adir clases css a elementos
function addClass( classname, element ) {
var cn = element.className;
if( cn.indexOf( classname ) != -1 ) {
return;
}
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}
// Funci—n para eliminar clases css a elementos
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}
function menu(opcion){
// Si pulsamos en el bot—n de "menu" entramos en el if
if(opcion=="menu"){
if(estado=="cuerpo"){
cuerpo.className = 'page transition right';
estado="menuprincipal";
}else if(estado=="menuprincipal"){
cuerpo.className = 'page transition center';
estado="cuerpo";
}
// Si pulsamos un bot—n del menu principal entramos en el else
}else{
// A–adimos la clase al li presionado
addClass('li-menu-activo' , document.getElementById("ulMenu").getElementsByTagName("li")[opcion]);
// Recogemos mediante ajax el contenido del html segœn la opci—n clickeada en el menu
xhReq.open("GET", "opciones/opcion"+opcion+".html", false);
xhReq.send(null);
document.getElementById("contenidoCuerpo").innerHTML=xhReq.responseText;
// Refrescamos el elemento iscroll segœn el contenido ya a–adido mediante ajax, y hacemos que se desplace al top
myScroll.refresh();
myScroll.scrollTo(0,0);
// A–adimos las clases necesarias para que la capa cuerpo se mueva al centro de nuestra app y muestre el contenido
cuerpo.className = 'page transition center';
estado="cuerpo";
// Quitamos la clase a–adida al li que hemos presionado
setTimeout(function() {
removeClass('li-menu-activo' , document.getElementById("ulMenu").getElementsByTagName("li")[opcion]);
}, 300);
}
}
我正在插入一些console.log行来执行,但onDeviceReady函数没有启动。
请查看我的代码并告诉我那里有什么问题。
谢谢。
已编辑:
console.log
ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
(index):85 cordova :: fired deviceready event!
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady
在实施Joerg的答案后完成控制台日志:
ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
index.js:33 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
cordova.js:633 Uncaught Function required as first argument!forceFunction @ cordova.js:633Channel.subscribe @ cordova.js:645document.addEventListener @ cordova.js:132(anonymous function) @ index.js:51j @ jquery-2.1.4.min.js:2k.fireWith @ jquery-2.1.4.min.js:2n.extend.ready @ jquery-2.1.4.min.js:2I @ jquery-2.1.4.min.js:2
(index):85 Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only.
(index):85 Ripple :: Environment Warming Up (Tea. Earl Gray. Hot.)
ripple.js:50 GET http://192.168.1.78:3000/config.xml 404 (Not Found)(anonymous function) @ ripple.js:50module.exports.initialize @ ripple.js:50_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13(anonymous function) @ ripple.js:38
ripple.js:50 POST http://192.168.1.78:3000/ripple/user-agent 404 (Not Found)(anonymous function) @ ripple.js:50setUserAgent @ ripple.js:39_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13_baton.pass @ ripple.js:13(anonymous function) @ ripple.js:38
(index):85 cordova :: Setting the user agent server side failed.
(index):85 cordova :: Initialization Finished (Make it so.)
index.js:3 ENTRANDO!!!!
index.js:16 ENTRANDO EN VAR APP FUNCTION()!!!
cordova.js:633 Uncaught Function required as first argument!forceFunction @ cordova.js:633Channel.subscribe @ cordova.js:645document.addEventListener @ cordova.js:132(anonymous function) @ index.js:51j @ jquery-2.1.4.min.js:2k.fireWith @ jquery-2.1.4.min.js:2n.extend.ready @ jquery-2.1.4.min.js:2I @ jquery-2.1.4.min.js:2
(index):85 Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only.
(index):85 cordova :: fired deviceready event!
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady
(index):85 deviceready has not fired after 5 seconds.
(index):85 Channel not fired: onCordovaConnectionReady
(index):85 Channel not fired: onCordovaInfoReady
答案 0 :(得分:1)
使用Cordova / Phonegap时最重要的事件是deviceready事件。这项活动很特别,来自cordova docs:
此事件的行为与任何事件处理程序中的其他事件不同 在事件被触发后注册将有其回调 函数立即调用。
另一方面,您使用jQuery,它需要具有文档就绪事件。
所以,你需要将它们放在一起并重写你的绑定函数:
bindEvents: function() {
$(document).ready(function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
});
},
<强>更新强>
在stackoverflow中有很多关于如何管理事件以及如何组织cordova应用程序主体结构的问题。这是一个基本脚本,您可以使用和扩展:
/**
* Starts the app by calling the function initialize();
*/
app.initialize();
// The main app starts here, put all your functions inside app!!
var app = {
/**
* If you have global variables, put them here. You call them e. g.: app.myStringVar
* Remember to put a comma at the end of each line!!
*
*/
myStringVar: "Hello",
myBoolVar: true,
/**
* Here is your first function, which is called above.
* Put in this function nothing more then the important event listener, like this one for jQuery AND the Cordova deviceready listener.
*/
initialize: function () {
/**
* First listen to the jQuery ready event, if you use jQuery, and then listen to cordova.
*
* If you use jQuery Mobile, then use:
*
* $(document).on("pageinit", function () {
* document.addEventListener("deviceready", app.onDeviceReady, false);
* });
*/
$(document).ready(function () {
document.addEventListener("deviceready", app.onDeviceReady, false);
/**
* You can put other Cordova listener here, for example the pause or resume listener:
*
* document.addEventListener("pause", app.onPause, false);
* document.addEventListener("resume", app.onResume, false);
*
*
*/
});
},
/**
* If the Cordova deviceready event is fired, this function is called. Put in this function all the basic logic for your app.
*
* Put all your other function below and call them e.g.: app.myFirstFunction();
*/
onDeviceReady: function () {
app.myFirstFunction("Hi, cordova!");
}, myFirstFunction: function (term) {
alert(term);
}
};