1

I'm try to access the router inside a function that is called by another function, and the error message is:

Uncaught TypeError: Cannot read property 'navTo' of undefined
sap.ui.controller.loginSuccess
request.onreadystatechange

I created a JSON model to connect in my server to authenticate the user, when I have a successful authentication, I call the loginSuccess from my controller.

Inside the controller I try to get the router to navigate in my pages.

login:function(){
    var login = new Login();

    login.loginAuth(
            this.byId("user").getValue(), 
            this.byId("passwd").getValue(), 
            this.loginSuccess, this.loginError );

    this.clear();

},

loginSuccess: function(type){
    var router = sap.ui.core.UIComponent.getRouterFor(this);
    if(type == "TIPO 1")
        router.navTo("MainPage", false);
    if(type == "TIPO 2")
        router.navTo("SupportMainPage", false);
    if(type == "TIPO 3")
        router.navTo("ManagerMainPage", false);
},

Why can't I access the methods of my controller inside this function? I tried to access the this.getView() and doesn't work too.

How can I solve this?

Thanks

mayconbelfort
  • 195
  • 1
  • 5
  • 17
  • 1
    try calling `console.log(this);` at the beginning of loginSuccess. when that is not the controller you will have to call the function in the right context. – herrlock Feb 19 '15 at 21:57
  • Herrlock, thanks for reply. How can I do this? – mayconbelfort Feb 20 '15 at 12:29
  • 1
    use loginSuccess.call(controller); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) – herrlock Feb 20 '15 at 12:57

1 Answers1

1

The this pointer is not pointing to your controller anymore. I guess it is either pointing to your Login() instance or window. To come around this issue you have several options:

login:function(){
    var login = new Login();
    login.loginAuth(
            this.byId("user").getValue(), 
            this.byId("passwd").getValue(), 
            $.proxy(this.loginSuccess, this), this.loginError );

    this.clear();
},

The $.proxy function makes sure that this points to the second parameter i.e. your controller. Another frequently used pattern is to add a parameter to your loginAuth function which is a this scope and call it like:

login.loginAuth(
            this.byId("user").getValue(), 
            this.byId("passwd").getValue(), 
            this.loginSuccess, this.loginError, this);

Your loginAuth function internally calls the given callback like this:

loginSuccess.call(scope, type);
Tim Gerlach
  • 3,390
  • 3
  • 20
  • 39