JavaScript onDeviceReady not firing

mvasco

I am creating my first Cordova project and I am new to JavaScript.

I am following some tutorials but now I am integrating some JavaScript code into index.js file.

Edited index.js following Joerg answer:

  // 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);

     }



}

I am inserting some console.log lines to follow the execution, but the onDeviceReady function is not launched.

Please take a look at my code and tell me what is wrong there.

Thank you.

EDITED:

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

Complete console log after implementing answer from 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
Joerg

The most important event when using Cordova/Phonegap is, the deviceready event. This event is special, from the cordova docs:

This event behaves differently from others in that any event handler registered after the event has been fired will have its callback function called immediately.

On the other hand you use jQuery, which needs to have the document ready event.

So, you need to put this together and rewrite your binding function like that:

bindEvents: function() {
        $(document).ready(function() {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        });
},

Update:

Here at stackoverflow are a lot of questions regarding how to manage the events and how to organize the main structure of a cordova app. Here is a basic script, which you can use and expand:

/**
 * 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);
    }
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related