SAPUI5 对话框问题

SAPUI5 Dialog issue

I have a dialog in my sapui5 application which when the "Yes" option is selected the user is taken to the home view, but it is saying my function is undefined.我是否正确地从对话框中调用函数?

这是我的代码:

加载主视图功能:

loadHome : function() {
                    this.router = sap.ui.core.UIComponent
                            .getRouterFor(this);
                    this.router.navTo("HomePage");
                },

我的对话:

cancelDialog : function() {                     
                    var oDialog1 = new sap.ui.commons.Dialog();
                    oDialog1.setTitle("Cancel Case");
                    var oText = new sap.ui.commons.TextView(
                            {
                                text : "Are you sure you want to cancel? Case data will not be saved"
                            });
                    oDialog1.addContent(oText);
                    oDialog1.addButton(new sap.ui.commons.Button({
                        text : "Yes",
                        press : function(){
                            this.loadHome();
                        }                       
                    }));
                    oDialog1.addButton(new sap.ui.commons.Button({
                        text : "No",
                        press : function() {
                            oDialog1.close();
                        }
                    }));
                    oDialog1.open();
                },

这两个函数都在创建控制器中。感谢您的帮助

问题出在“是”按钮的事件处理程序中。在此处理程序中,"this" 指向按下的按钮而不是控制器。要获得对控制器的引用,您可以简单地调用 bind(this)。或者,您也可以只在处理程序外部存储对控制器的引用并稍后访问它("var that = this;" 等等...)==>闭包...

Here 是 bind(this):

的工作示例
//...
oDialog1.addButton(
  new sap.ui.commons.Button({
    text : "Yes",
    press : function(){
      this.loadHome();
    }.bind(this)                       
  })
);
//...

这是另一种方法(that=this...):

//...
var that = this;
oDialog1.addButton(
  new sap.ui.commons.Button({
    text : "Yes",
    press : function(){
      that.loadHome();
    }
  })
);
//...

除此之外,您应该考虑使用 sap.m 控件而不是 sap.ui.commons。然后还要考虑为您的对话框使用片段,这将使代码更好读 + 更好地重用对话框...Here I have published a nice template that gives you and idea. Maybe you would like to check my other tutorials 以及...

我觉得Nabi的回答已经很清楚了。但是,请记住,在有限数量的情况下,您可以通过 id 获取对象。例如

var oController = sap.ui.getCore().byId("id2").getController()

会给你一个控制器的引用到带有 id2 的视图。但是请不要滥用此方法,因为通常只访问 this 指针指定的有限功能范围而不是应用程序中的所有对象是一件好事。