Reputation: 123
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
});
});
Upvotes: 1
Views: 1723
Reputation: 5206
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.
Upvotes: 4