0

I was trying to make my code look more clean by storing some function code in a own function. However this did not work out. No error is logged in the console.

This is my code:

onPressScan: function() {
sap.ndc.BarcodeScanner.scan(
    // calling the function at this point works
    function(mResult) {
        if (!mResult.cancelled) {
            // call another function from the same controller
            this.handleData(mResult.text);
        }
    },
    function(Error) {
        sap.m.MessageBox.error("Scanning failed due to following error: " + Error, {
            title: "Error while scanning"
        });
    }
),

handleData: function(data) {
sap.m.MessageBox.success("Calling function worked: " + data, {
    title: "Success"
});
}

For testing purpose I minimized the handleData function to a minimum. What I just tried was calling the function one layer above (not threw two function calls...). This works. However, I need to call the function where you can see it in the code. How can I achieve that?

Thank you.

C. Ubkcah
  • 273
  • 13
  • 33

1 Answers1

0

your context has changed and this in context is no longer the controller.

add a handle to this at the correct point - e.g.

var that = this;

Then change the code to where you are wanting to access this function off the controller:

that.handleData(mResult.text);

Your code should work of change to as below:

onPressScan: function() {
sap.ndc.BarcodeScanner.scan(
    var that = this;
    function(mResult) {
        if (!mResult.cancelled) {
            that.handleData(mResult.text);
        }
    },
    function(Error) {
        sap.m.MessageBox.error("Scanning failed due to following error: " + Error, {
            title: "Error while scanning"
        });
    }
),

handleData: function(data) {
sap.m.MessageBox.success("Calling function worked: " + data, {
    title: "Success"
});

}

Bernard
  • 1,208
  • 8
  • 15