SAPUI5 - this.getView() is not a function

Rubens Cesar picture Rubens Cesar · May 3, 2017 · Viewed 7.7k times · Source

I am trying to get the input value, but when I call the function I get the error this.getView() is not a function

Below is the function in controller

    handleConfirmationMessageBoxPress: function(oEvent) {
        var bCompact = !!this.getView().$().closest(".sapUiSizeCompact").length;
        MessageBox.confirm(
            "Deseja confirmar a transferência?", {
                   icon: sap.m.MessageBox.Icon.SUCCESS,
                   title: "Confirmar",
                    actions: [sap.m.MessageBox.Action.OK, sap.m.MessageBox.Action.CANCEL],
                    onClose: function(oAction) {
                      if (oAction == "OK"){
                          var loginA = this.getView().byId("multiInput").getValue();
                          alert(loginA)
                          MessageToast.show("Transferência efetuada");

                      }else{
                         // MessageToast.show("Transferência não cancelada");
                           }

                        },
                        styleClass: bCompact? "sapUiSizeCompact" : ""
            }
        );
    }

And here is the input in the view

   <m:Input id="multiInput" value="teste" placeholder="Clique no botão ao lado para buscar o usuário" showValueHelp="true" valueHelpRequest="valueHelpRequest" width="auto"/>

Answer

Serban Petrescu picture Serban Petrescu · May 3, 2017

I would assume that you get that error on the second this.getView() from inside the callback. You are getting this because of the way that this works in JavaScript. See the following MDN documentation: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this.

In a nutshell, calling a function freely without it being referenced from "inside" an object (i.e. fnFunction() vs oObject.func()), will cause the this to point to either nothing or the window object. To get the right this, you can either use the arrow function declaration, the jQuery.proxy method or the .bind function:

onClose: oAction => {
   // your code
}

// OR

onClose: function(oAction) {
   // your code
}.bind(this)

// OR

onClose: jQuery.proxy(function(oAction) {
   // your code
}, this)