SAPUI5 在 sap.ui.controller 中使用自定义函数

SAPUI5 using custom functions in sap.ui.controller

我试图在另一个函数调用的函数中访问路由器,错误消息是:

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

我创建了一个 JSON 模型来连接我的服务器来验证用户,当我成功验证时,我从我的控制器调用 loginSuccess。

在控制器内部,我尝试让路由器在我的页面中导航。

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);
},

为什么我不能在这个函数中访问我的控制器的方法? 我尝试访问 this.getView() 但也不起作用。

我该如何解决这个问题?

谢谢

this 指针不再指向您的控制器。我猜它要么指向您的 Login() 实例,要么指向 window。要解决此问题,您有多种选择:

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

    this.clear();
},

$.proxy 函数确保 this 指向第二个参数,即您的控制器。另一个经常使用的模式是向 loginAuth 函数添加一个参数,它是一个 this 范围,并像这样调用它:

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

您的 loginAuth 函数在内部像这样调用给定的回调:

loginSuccess.call(scope, type);