Я создаю свой первый проект в Кордове, и я новичок в JavaScript.JavaScript onDeviceReady not firing
Я следую некоторым учебникам, но теперь я интегрирую код JavaScript в файл index.js.
Отредактированные 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
Спасибо, Йох, я попробую сейчас. – mvasco
Я внедрил ваше предложение, но, я думаю, результат тот же. Вопрос изменен, чтобы включить полный журнал консоли. – mvasco
Вы делаете все вместе, я обновляю свой ответ в течение следующего часа. – Joerg