我在Titanium mobile中有一个QRcode扫描程序CommonJS模块,我想添加成功并取消回调。
但是我的函数在模块中总是未定义。
我的模块:
var scanner = null,
successCallback = null,
cancelHandler = null;
function AndroidScanner(allowRotation, displayedMessage, allowMenu, allowInstructions, useLED){
this.scanner = require("ti.barcode");
if(allowRotation)
this.scanner.allowRotation = allowRotation;
if(displayedMessage)
this.scanner.displayedMessage = displayedMessage;
if(allowMenu)
this.scanner.allowMenu = allowMenu;
if(allowInstructions)
this.scanner.allowInstructions = allowInstructions;
if(useLED)
this.scanner.useLED = useLED;
};
//successListener changes the event to a common one for iOS and Android
AndroidScanner.prototype.successListener = function(event) {
Ti.API.info("Successcallback get: "+JSON.stringify(this.successCallback));
this.successCallback({barcode: event.result});
};
//Starts the scanner, pass the view to add the scanner to
AndroidScanner.prototype.startScanning = function(view) {
this.scanner.addEventListener('success', this.successListener);
this.scanner.addEventListener('cancel', this.cancelHandler);
this.scanner.capture({
animate : true,
overlay : null,
showCancel : true,
showRectangle : true,
keepOpen : false
});
};
//Removes event listeners from the scanner
AndroidScanner.prototype.stopScanning = function() {
this.scanner.removeEventListener('success', this.successHandler);
this.scanner.removeEventListener('cancel', this.cancelHandler);
};
//Add a success handler
AndroidScanner.prototype.successHandler = function(handler) {
Ti.API.info("Successhandler set: "+JSON.stringify(handler));
this.successCallback = handler;
};
//Add a cancel handler
AndroidScanner.prototype.cancelHandler = function(handler) {
Ti.API.info("Cancelhandler set: "+JSON.stringify(handler));
this.cancelHandler = handler;
};
module.exports = AndroidScanner;
在alloy.js中:
if(OS_ANDROID) {
var AndroidScanner = require("/ui/AndroidScanner");
Alloy.Globals.scanner = new AndroidScanner(
true,
'',
false,
false,
false
);
}
Alloy.Globals.scanner.successHandler(function(e) {
Alloy.Globals.barcodeScannerOn = false;
//on successful scanning we know that windows is back
Alloy.Globals.barcodeScanSuccesfull = true;
Alloy.Globals.barcodeScanCanceled = false;
Alloy.Globals.scanner.stopScanning();
Alloy.Globals.barcodeScanResult = e.barcode;
Ti.API.info('scan result' + JSON.stringify(Alloy.Globals.barcodeScanResult));
});
Alloy.Globals.scanner.cancelHandler(function(e) {
Alloy.Globals.barcodeScannerOn = false;
Alloy.Globals.barcodeScanCanceled = true;
Alloy.Globals.barcodeScanSuccesfull = false;
Alloy.Globals.scanner.stopScanning();
});
日志始终显示:
[INFO] : Successhandler set: undefined
[INFO] : Cancelhandler set: undefined
为什么会这样?