cancel
Showing results for 
Search instead for 
Did you mean: 

couldn't use this.getView() in button press function

Former Member
0 Kudos

Hi Professionals,

I couldn't use this.getView() and .getValue() in my button press, why ??

here is my button code


var updatebtn = new sap.m.Button({
text: "Update",
press: function(){
var tem = {};
tem.DISHESID = this.getView().byId("browniesiddialoginput").getValue();
tem.DISHESNAME = this.getView().byId("browniesnamedialoginput").getValue();
tem.DISHESDESC = this.getView().byId("browniesdescdialoginput").getValue();
tem.DISHESPRICE = this.getView().byId("browniespricedialoginput").getValue();
}    
});

and this is the error I get

Uncaught TypeError: this.getView is not a function

Thanks.

Accepted Solutions (0)

Answers (3)

Answers (3)

Former Member

Hi

you need to bind the this-context for the event handler "press":

var updatebtn = new sap.m.Button({
text: "Update",
press: function(){
var tem = {};
tem.DISHESID = this.getView().byId("browniesiddialoginput").getValue();
tem.DISHESNAME = this.getView().byId("browniesnamedialoginput").getValue();
tem.DISHESDESC = this.getView().byId("browniesdescdialoginput").getValue();
tem.DISHESPRICE = this.getView().byId("browniespricedialoginput").getValue();
}.bind(this)    
});

As otherwise this in your case would be the control....

former_member365727
Active Contributor
0 Kudos

this in your code refers to button event handler...not the controller reference

Store controller reference in a global variable of the view controller from init method, so it can be accessed from any method

sap.ui.define([
     "sap/ui/core/mvc/Controller"
], function(Controller){
       "use strict";
       
       var oController;    //variable to store controller reference
      
      return Controller.extend("com.controller.App", {
          init: function(){
              oController = this;
          },

        sampleMethod: function(){
           var updatebtn = new sap.m.Button({
              text: "Update",
              press: function(){
                  var tem = {};
                  //replace 'this' with oController
                  tem.DISHESID = oController.getView().byId("browniesiddialoginput").getValue();
                  tem.DISHESNAME = oController.getView().byId("browniesnamedialoginput").getValue();
                  tem.DISHESDESC = oController.getView().byId("browniesdescdialoginput").getValue();
tem.DISHESPRICE = oController.getView().byId("browniespricedialoginput").getValue(); } }); } }); });
junwu
Active Contributor
0 Kudos

definitely bad idea

former_member365727
Active Contributor
0 Kudos

Hi Jun,

I have used this approach in projects...this is similar to using 'that = this'.

Can you let me know if anything is wrong with this code, so that I can correct project code and myself 🙂

junwu
Active Contributor
0 Kudos

if that code is in view, "this" means view. that is not what you want....