I got an external js file loaded to my Angular project and one of the function is a callback function which I have assigned to one of my functions fnBarcodeScanned(scan).
Everything works correctly as I'm getting alert with correctly scanned barcode but next line doesn't assign a barcode to my local variable this.scanData.
export class HomeComponent implements OnInit {
scanData: string;
ngOnInit() {
}
fnScanEnable() {
EB.Barcode.enable({ allDecoders: true }, this.fnBarcodeScanned);
this.scanData = "enabled: press HW trigger to capture.";
}
fnBarcodeScanned(scan) {
alert(scan.data);
this.scanData = "barcode: " + scan.data;
}
fnScanDisable() {
EB.Barcode.disable();
this.scanData = "disabled: press 'enable' to scan.";
}
}
How can I bind fnBarcodeScanned(scan) function? As it seems to me it lost binding with the component when it was passed to callback.
You can either use bind() or arrow function
Using bind():
fnScanEnable() {
EB.Barcode.enable({ allDecoders: true }, this.fnBarcodeScanned.bind(this));
this.scanData = "enabled: press HW trigger to capture.";
}
Using arrow function:
fnBarcodeScanned = (scan) => {
alert(scan.data);
this.scanData = "barcode: " + scan.data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With