Search code examples
javascriptonsen-uimonaca

Monaca.getDeviceId() not able to set to variable


I have tried multiple ways of setting the device id to a variable once so it can be used in other functions without requiring the monaca callback. This code does not work:

function getDevID(){
    monaca.getDeviceId(function(id){
        return id;
    });
}

Nor does this:

var devid = monaca.getDeviceId(function(id){return id;});

So basically, how can I set the device ID to a variable for repeated use throughout my app?

Update: Based on the comment of the possible duplicate to asynch calls, I went back and analyzed that and found it to be correct. Although not technically a duplicate post, the answer is within that post about asynch workflow. The solution to my issue can be resolved this way:

var devid = '';

document.addEventListener ("deviceready", onDeviceReady, false);
function onDeviceReady() {
   monaca.getDeviceId(function(id){
      devid = id;
   });           
} 

I then am able to use devid anywhere needed post load.


Solution

  • Using deviceready event listener, as you did, is for sure the best approach, just remember to remove the Event Listener when you are done. Nevertheless, if you are using Onsen UI, you can also use ons.ready(), which waits for the DOM to be initialized. It will be probably fired a couple of ms after deviceready, but will save you some code and will have the same result.