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

Failed to complete the Vue.js project build process in the Gitlab CI/CD pipeline

During the deployment of my project using Gitlab CI/CD, I encountered an issue with dependencies. Everything functions correctly locally, but not within the pipeline. .gitlab-ci.yml: stages: - build-frontend - build-backend image: lnkra/<...project n ...

Unable to modify preset choices in radio checkboxes

I am a paramedic with no prior experience in this area. My task involves completing numerous patient forms that contain excessive fields, creating redundancy. To streamline this process, I am attempting to script a solution that will automatically populat ...

Testing VueJS Components: Verifying the Presence of a Specific CSS Class

I can't seem to get my unit test for a VueJS app to work properly. The test is supposed to check if the template contains a div element with the class name "version", but I keep getting an error message that says undefined is not a constructor (evalu ...

Ajax: setInterval function successfully runs code but does not refresh the HTML output

I have multiple div elements in my code. I want to update the HTML content inside them based on an API request. The updating process works fine, but the HTML content doesn't refresh visually (meaning that even if I receive a new result from the API, t ...

Ajax implementation for handling URL action parameters

I am currently facing challenges in passing data from a view to a controller using parameters. My goal is to pass these parameters when I select a row from a table and click on a button that triggers the ShowTasks() function. Here is the C# controller cod ...

Images displayed alongside webpage contents

I'm having trouble getting these photos to display in the same row. Any suggestions on what I should change? https://i.stack.imgur.com/EbvmR.png I've attempted using float left and other commands, but one picture continues to stay in the lower r ...

trigger opening a bootstrap modal programmatically

I have a modal setup using Bootstrap with the code below: <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true" > &l ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...

Implementing the linking of a URL to an HTML hidden button that is dynamically displayed through a Javascript program

I'm currently developing a basic webpage that has a feature allowing users to download the final result as an image file in the last step. To achieve this, I've added a hidden HTML button for downloading the result image and used CSS to set its ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

Something is not quite right when the page is loading in a Ruby on Rails application

In the process of developing a wiki clone, I am faced with an issue involving JavaScript. When I navigate to a specific page by clicking on a link, the JavaScript does not function properly until I refresh the page. The JavaScript aspect mainly involves an ...

What is the best method to substitute a comma and period with just a period in a textarea

Creating a text area with auto-replacing characters like straight quotes, double dashes to em dash, and double spaces to single space was simple. However, I'm facing difficulty in adding a script for replacing certain characters: word . as word. wor ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...

Guidelines for choosing AngularJS checkboxes to exclusively choose distinct matching items

Need help with selecting common items using Angular checkboxes. Below is the mock UI-Table: Order Id | Delivery Mode | Select 1 | Speed | ::checkbox:: 2 | Normal | ::checkbox:: 3 | Contractor | ::che ...

Mastering the control of a camera in three.js using a combination of keyboard and mouse navigation techniques

I have been working on a 3D environment in WEB GL using three.js, previously using orbitcontrols.js as shown in this project: http://codepen.io/nireno/pen/cAoGI. Recently, I came across a different method of navigating the environment using the W, A, S, D ...

Conceal a column within a table by double-clicking

I'm working on a project with a table, and I'd like to implement a feature where a column hides when double-clicked. I've seen various solutions for hiding columns on Stack Overflow, but I could use some guidance on where to add the ondblcli ...

Generating a linked pledge with AngularJS

I need to create a linked commitment for my service provider: this.$get = function($q, $window, $rootScope) { var $facebook=$q.defer(); $rootScope.$on("fb.load", function(e, FB) { $facebook.resolve(FB); }); $facebook.api = functi ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

Using JSON to pass a function with parameters

I have a small issue that I'm struggling to solve. My dilemma lies in sending a JSON with a function, along with parameters. Typically, it's easy to send a function in JSON like this: var jsonVariable = { var1 : 'value1', var2 : &apos ...