Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding callback function in Angular

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.

like image 799
Whistler Avatar asked Oct 27 '25 05:10

Whistler


1 Answers

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;
 }
like image 53
Harun Yilmaz Avatar answered Oct 29 '25 19:10

Harun Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!