-

- -

Saturday, December 17, 2016

107a XDK: How Does Cordova Barcode Scanner App Work?


107a XDK: How Does Cordova Barcode Scanner App Work?
This tutorial explains the codes used in the previous tutorial, http://xdk-steps.blogspot.my/2016/12/107-xdk-create-cordova-barcode-scanner.html .
This project contains three core files ie index.html, app.js and init-app.js. If you are new to these files, read here first, http://xdk-steps.blogspot.my/2016/12/105a-xdk-how-does-cordova-starter-app.html .
However, the important files that we will look at are index.html and app.js

File: index.html

This file contains the UI code for the apps.
The above HTML codes produce the following output.
The button contains an attribute onclick which will call the function scan() when the onclick triggers.
Where are the codes for scan()? They are in the file app.js.

File: app.js

The following is an excerpt of the file app.js showing the codes for function scan().

..
function scan() {
    "use strict";
    var fName = "scan():";
    console.log(fName, "entry");
    try {
        if (window.tinyHippos) {
            thirdPartyEmulator();
            console.log(fName, "emulator alert");
        } else {
            cordova.plugins.barcodeScanner.scan(
                function (result) {
                    console.log(fName, "Scanned result found!");
                    alert("We got a barcode!\n" +
                        "Result: " + result.text + "\n" +
                        "Format: " + result.format + "\n" +
                        "Cancelled: " + result.cancelled + "\n\n" +
                        "You may use the " + result.format + " - '" + result.text + "' to look up your product in any UPC database like http://www.upcdatabase.com/");
                },
                function (error) {
                    alert("Scanning failed: " + error);
                }
            );
        }
    } catch (e) {
        console.log(fName, "catch, failure");
    }
    console.log(fName, "exit");
}
...
The function cordova.plugins.barcodeScanner.scan(...) is an asynchronous function.
That means, at this line, the program control will call cordova.plugins.barcodeScanner.scan() to do the barcode scanning job. Once the job is done, the result is returned back to the inline function. This function displays an alert message containing the result data.
Cordova Plug in has made the barcode scanning process simpler.

No comments:

Post a Comment