Vue is unable to capture Cordova events

Creating a hybrid app using Cordova while incorporating VueJS for routing and AJAX requests has presented some challenges for me.

Despite my efforts, I have been unable to capture certain Cordova events. Even the essential deviceReady event seems to be eluding me. Below is a snippet of my code:

require('./bootstrap');


var Vue = require('vue');
var VueRouter = require('vue-router');

Vue.use(VueRouter);

// Components
Vue.component('test', require('./Vue/components/test.vue'));
Vue.component('mainnav', require('./Vue/partials/mainnav.vue'));

// Route components
const Home = Vue.component('home', require('./Vue/pages/home.vue'));
const Login = Vue.component('login', require('./Vue/pages/auth/login.vue'));
const Register = Vue.component('register', require('./Vue/pages/auth/register.vue'));
const notFound = Vue.component('notFound', require('./Vue/pages/404.vue'));

// Define routes
const routes = [
    { path: '', component: Home },
    { path: '/', component: Home },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '*', component: notFound }
];

const router = new VueRouter({
    mode: 'history',
    routes // short for routes: routes
});

const vueApp = new Vue({
    router,
    mounted: function(){
        //alert('VueJS is ready!');
        document.addEventListener('deviceReady', this.onDeviceReady, false);
    },
    methods: {
        onDeviceReady: function() {
            alert('Device is ready!');
        }
    }
}).$mount('#app');

I suspect that the issue might arise from the device being ready before Vue is fully active. How can this timing conflict be resolved?

We do have access to other functionalities such as the vibration-plugin through both the Vue root-instance and a specific Vue component:

export default {
    data() {
        return {
            vibrateDuration: 5000,
        };
    },
    methods: {
        letsVibrate: function(){
            navigator.vibrate(this.vibrateDuration);
        }
    }
}

Any suggestions on how to effectively capture the device ready event within the Vue framework?

Answer №1

Perhaps it's all about dealing with concurrency issues. Consider implementing simple semaphore locks to trigger a function only when both conditions are met (not verified, but the concept is there):

let deviceInitialized = false
let vueRendered = false

const myVueApp = new Vue({
  router,
  mounted: function(){
    vueRendered = true
    if (deviceInitialized) myVueApp.everythingReady()
  },
  methods: {
    everythingReady: function() {
        alert('Vue rendered and everything is set')
    }
  }
}).$mount('#app')

document.addEventListener('deviceInitialized', () => {
  deviceInitialized = true
  if (vueRendered) myVueApp.everythingReady()
}, false)

Answer №2

When developing Vue applications, remember to include

<script src="cordova.js"></script>
in your public/index.html file.

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title>My app</title>
  </head>
  <body>
    <script src="cordova.js"></script> <!-- Make sure to add this line -->
    <div id="app"></div>
    <noscript>
      <strong
        >We're sorry but ia doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong
      >
    </noscript>
  </body>
</html>

Answer №3

Give this a shot:

initializeApp = new App({ 
   //...
    functions: { 
          onReadyDevice: function() {
               alert('Your device is all set!');
            } 
       } 
});

deviceCheck.addEventListener(
      'readydevice', 
       initializeApp.onReadyDevice
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passport.js is throwing an error due to an unrecognized authentication

I need to implement two separate instances of Passport.js in my application - one for users and one for admins, both using JWT authentication. According to the official documentation, the way to differentiate between them is by giving them unique names. W ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

Trouble encounter when attempting to use Ajax for inserting data into a MySQL database

I have been attempting to perform a simple database insert from my phonegap application but I am encountering an issue where the ajax function is returning the entire save.php file to my success function instead of adding anything to the database. I even t ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

Updating variable value in a Javascript function

I'm currently working on a signup page and I need to verify if an email address already exists in the database. var emailnum = getEmailCount(`select * from contactinfo where email='${email}'`); console.log(emailnum); // Output shows ...

Tips for effectively organizing a collapsible list

Here is a list that I have: <ul> <li><span class="Collapsable">item 1</span> <ul> <li><span class="Collapsable">item 1.1</span></li> </ul> </ul> I am looking to create ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Trying to fetch an image from a server using VueJS?

How can I fetch an image from the server in Vue.js and display it on a Blade template in Laravel? The issue seems to be with displaying the image using the code below. <tr v-for="post in posts"> <td>{{post.title}}</td> <td&g ...

implementing toggle functionality for an array of items in ReactJS

I have an array and I am trying to create a show/hide feature for each item based on toggling. When I click on one item, it should expand while simultaneously hiding the previously expanded item. Here is the code snippet I have been working on: class App e ...

Flying around in every essential element within a Vue template

Recently, I made the switch to Typescript for Vue and decided to enable the Volar extension. However, after doing so, I noticed that every HTML intrinsic element (such as section and img) is now being flagged as an error: JSX element implicitly has type &a ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

React component failing to render even when event is triggered

For my latest project, I am creating a blog using react, next.js, and json-server. The blog is coming along nicely with dynamically loaded blog posts and UI elements. However, I've hit a roadblock when it comes to loading comments dynamically. The sp ...

Change the background color of all cells in a Bootstrap table by hovering over a single cell

Here is the code for a bootstrap table: <body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0"> <div class="container-fluid h-100"> <div class="row float-right align-items-center" style="height: 5%;"> ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

JavaScript Transforming an Array into an Object

After working with node and redis for a while, I've encountered an issue. When using hgetall in redis, it returns an object. { uid: '6203453597', first_name: 'Name', last_name: 'Surname', gender: 'male& ...

The error function is consistently triggered when making an Ajax POST request, even though using cURL to access the same

I have been using Ajax's POST method to retrieve a JSON response from the server. However, whenever I click the button on my HTML page, the Ajax function always triggers the error function, displaying an alert with the message "error." Below is the co ...

I'm puzzled by the fact that even though the api routes in tenant.php with Laravel VueJs are showing a 200 OK status code in the network tools, I'm still getting a blade as a response

Let me start by mentioning that I am currently engaged in a project that is based on Laravel VueJs with tenancy for laravel v3 package. To provide some context, I can successfully log in to my [email protected] account registered at any created tenan ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...