Why is this Javascript library available in browser but not in PhoneGap?

47 views Asked by At

I have defined a library in Javascript that works great when I am in a browser but whose name isn't found when running under PhoneGap on my device.

The library is defined as so:

(function(bsdi, $) {
    bsdi.SomeName = "XYZ";
    bsdi.addDays = function (date, days) { ...stuff here...}
    ....
}(bsdi = window.bsdi || {}, jQuery));

Later, in a .js file that is loaded last, I have:

function knockoutFn() {
    var self = this;
    if (bsdi.SomeName == "XYZ") {  <<--- CRASHES HERE, "bsdi not defined" but only on Device
       ...stuff here... 
    }
}

// Happens to use Knockout...
var koFn = new knockoutFn();
ko.applyBindings(koFn);

function init() {
    if (isPhoneGap) {
        document.addEventListener("deviceready", onDeviceReady, false);
    }
    else {
        koFn.InitPage();
    }
}

function onDeviceReady() {
    // Now safe to use the Cordova API
    koFn.InitPage();
}

What happens is that a normal web browser handles this just fine. However, when I download to my iPhone using the PhoneGap Build app, it gets to "bsdi.SomeName" and crashes because bsdi is not defined. I thought that my method for defining the bsdi library was correct but, obviously, there is something in PhoneGap that doesn't like this. Note that "isPhoneGap" is true and we do use the addEventListener on the device.

Any ideas are greatly appreciated!

UPDATE: On a hunch, I tried moving the bsdi object into the same .js file as the code that uses it. In this case, it finds the object and uses it correctly. When it is an external file, however, it fails. And yes, I have triple-checked that the file exists and is at the correct location. Again, it works fine in a browser!

1

There are 1 answers

2
Pointy On

If window.bsdi isn't defined, then (as posted in your question) your initialization code never ensures that window.bsdi is defined by the time the code is finished. All it does is add those properties to the new empty object passed in, but that won't have any effect on anything once the initialization function is finished.