Javascript Ondeviceready Not Firing
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 f
Solution 1:
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);
}
};
Post a Comment for "Javascript Ondeviceready Not Firing"