Community
cancel
Showing results for 
Search instead for 
Did you mean: 
madson_g_
Beginner
105 Views

Execute after app is ready

Jump to solution

How do I proceed to run a function after all elements have been loaded? I tried somethings like onload window, document.ready and even the onDeviceReady but it hasn´t worked so fine.

I have a GCM function running when the app is loaded. Now I want to call another function after I receive the token, because I need it to handle it with the db.

GCM function on index.html:

<script type="application/javascript">
        
        var pushNotification;
        var token;
        
            function onDeviceReady() {
                
                //$.ui.useOSThemes=false;
                
                $("#console").append('<p>-> Aplicativo iniciado!</p>');
                
                // Instanciando plugin Push...
                pushNotification = window.plugins.pushNotification;

                // Iniciar serviço de Push no aplicativo...
                pushNotification.register(
                    function (result) {
                        $("#console").append('<p>-> SUCESSO: '+ result+'</p>');
                    }, 
                    function (error) {
                        $("#console").append('<p>-> ERRO: '+error+'</p>');
                    }, 
                    {
                        "senderID":"mysenderID",
                        "ecb":"capturarEventos"
                    }
                );
                
            }
            
            // capturar notificações recebidos da API Google Cloud Messaging (GCM)...
            function capturarEventos(e) {
                
                $("#console").append('->-> EVENTO CAPTURADO:' + e.event);
                
                switch( e.event )
                {
                    // Dispositivo registrado no GCM!!!
                    case 'registered':
                            
                        $("#console").append('<p>-> APARELHO REGISTRADO:' + e.regid+'</p>');
                        token = e.regid;
                        $("#console2").append(token);
                        $("#hidden-input").attr('value', token);
                        console.log("TOKEN = " + e.regid);
                        break;
                    
                    // Chegou uma notificação push!!!
                    case 'message':
                        
                        // Verificar se push message chegou com o app aberto (em foreground)...
                        // Em caso positivo, lançamos um alerta (som, janela, etc.) para chamar atenção...  
                        if (e.foreground)
                        {
                            $("#console").append('<p>-> CAPTURADO PUSH COM APP ABERTO!</p>');
                        }
                        else
                        {	
                            // caso contrário, foram lançados porque o usuário tocou uma notificação na bandeja de notificação...
                            if (e.coldstart)
                                $("#console").append('<p>-> CAPTURADO PUSH COM APP EM COLDSTART!</p>');
                            else
                                $("#console").append('<p>-> CAPTURADO PUSH COM APP EM BACKGROUND!</p>');
                        }

                        // Compondo mensagem...
                        $("#console").append('<p>-> MENSAGEM: ' + e.payload.message + '</p>');
                        
                        break;
                    
                    case 'error':
						  $("#console").append('<p>-> ERRO:' + e.msg+'</p>' );
                        break;
                    
                    default:
						  $("#console").append('<p>-> EVENTO: Desconhecido, um evento estranho foi capturado.</p>');
                        break;
                }
            }

          document.addEventListener('app.Ready', onDeviceReady, true);
</script>

New function to be run only after e.regid has been set to var token.

function checkUser(){
    
                //var checkToken = "Grosselli";

                var dataString = "token="+token+"&get_user=";
                var $server;
                $server = 'http://mywebsite.com/project';

                $.ajax({
                    type: "post",
                    url: $server+"/checkUser.php",
                    data: dataString,
                    success: function(result, jqXHR){
                        alert(result);
                        console.log(JSON.stringify(result));

                        var resulting = $.parseJSON(result);

                        $.each(resulting, function(index, item){
                            var db_token = item.TOKEN;
                            alert(db_token);
                            alert(token);

                            if(db_token == token){
                                activate_page("#pageareas");
                            }else{
                                activate_page("#mainpage");
                            }

                        });


                    },
                    error: function(jqXHR, status){

                        alert("Sem conexão com a internet");
                        activate_page("#errorpage");

                    }
                });

            }

 

Tags (2)
0 Kudos
1 Solution
Zhen_Z_Intel
Employee
105 Views

Hi, if you want to call a function after all elements have been loaded, the easiest way is to add a "setTimeOut()" function. For example,

document.addEventListener('deviceready',function(){
                setTimeout(function(){
                 //your code here
                }, 3000);
            },false);

 

View solution in original post

2 Replies
PaulF_IntelCorp
Employee
105 Views

See the "hello cordova" example which uses the "xdk/init-dev.js" file which generates an "app.Ready" event to combine several ready events. From there, initialize your app. There are lots of comments in the app files to help you understand. See the "js/init-app.js" file for the function that is waiting on the "app.Ready" event.

Zhen_Z_Intel
Employee
106 Views

Hi, if you want to call a function after all elements have been loaded, the easiest way is to add a "setTimeOut()" function. For example,

document.addEventListener('deviceready',function(){
                setTimeout(function(){
                 //your code here
                }, 3000);
            },false);

 

View solution in original post

Reply