4

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.

1 Answer 1

3

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;
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Could you try converting fnScanEnable() to arrow function too?
still no change
Then I don't know what else to do. Can you create a project at stackblitz.com so that I can help you further?
That is not possible as external js file only works when on handheld device. The functions works ok when I dont use angular but simple in <script></script>. But I want to integrate this with angular app.
Maybe there is other way I could pass data from this function to component?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.