0

Is there any way to call SAP UI5 controller function inside an jQuery syntax written inside init() function of controller? What I meant is I have written below code snippet inside init() of user.controller.js. I have a function checkId() written inside that same controller which I want to call in the below snippet.How to do that? My code:

    $(window).load(function(){
       $("#myid").mousedown(function(){
         this.checkId(); //returns is not a function
       });
    });
santhosh
  • 461
  • 4
  • 15
VyomeshV
  • 57
  • 8
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Boghyon Hoffmann May 01 '18 at 20:09

1 Answers1

2

This is very closely related to the way in which the this keyword works in JavaScript. Check out How does the "this" keyword work? for more details.

You have three different possibilities to overcome the issues that you face:

1) Alias the this (store it into a variable):

var oController = this;
$(window).load(function(){
    $("#myid").mousedown(function(){
         oController.checkId();
    });
});

2) Rebind the this context for your inner functions (using e.g. .bind or jQuery.proxy):

$(window).load(function(){
    $("#myid").mousedown(function(){
         this.checkId();
    }.bind(this));
}.bind(this));

3) Use ES6 arrow functions (if you don't face problems related to browser support or if you have a transpilation build setup):

$(window).load(() => $("#myid").mousedown(() => this.checkId()));

Also, you should avoid as much as possible to manually add DOM event handlers in UI5. You could simply use a UI5 button and attach your method to the UI5 press event instead.

Serban Petrescu
  • 4,734
  • 2
  • 14
  • 31