UI5-文档-4.33-Routing Back and History

现在我们可以导航到细节页面并显示发票,但是还不能回到概览页面。我们将向细节页面添加一个back按钮,并实现一个函数,再次显示概述页面。

Preview

 

A back button is now displayed on the detail page

Coding

You can view and download all files at Walkthrough - Step 33.

 

webapp/view/Detail.view.xml

<mvc:View
        controllerName="sap.ui.demo.walkthrough.controller.Detail"
        xmlns="sap.m"
        xmlns:mvc="sap.ui.core.mvc">
        <Page
               title="{i18n>detailPageTitle}"
               showNavButton="true"
               navButtonPress="onNavBack">
               <ObjectHeader
                       intro="{invoice>ShipperName}"
                       title="{invoice>ProductName}"/>
        </Page>
</mvc:View>

 在detail页面上,我们通过将参数showNavButton设置为true告诉控件显示一个back按钮,并注册一个在按下back按钮时调用的事件处理程序。

webapp/controller/Detail.controller.js

sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/core/routing/History"
], function (Controller,History) {
        "use strict";
        return Controller.extend("sap.ui.demo.walkthrough.controller.Detail", {
               onInit: function () {
                       var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
                       oRouter.getRoute("detail").attachPatternMatched(this._onObjectMatched, this);
               },
                _onObjectMatched: function (oEvent) {
                       this.getView().bindElement({
                               path: "/" + oEvent.getParameter("arguments").invoicePath,
                               model: "invoice"
                       });
               },
               onNavBack:function(){
                       var oHistory =History.getInstance();
                       var sPreviousHash = oHistory.getPreviousHash();
 
                       if(sPreviousHash !==undefined){
                               window.history.go(-1);
                       }else{
                               var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
                               oRouter.navTo("overview",{},true);
                       }
               }
        });
});

 我们加载了一个新的依赖项,它帮助我们管理sap.ui.core中的导航历史。路由命名空间,并将事件处理程序的实现添加到我们的详细页面控制器。

在事件处理程序中,我们访问导航历史记录并尝试确定前面的散列。与浏览器历史记录相反,只有在应用程序中已经发生导航步骤时,我们才会得到有效的结果。然后,我们将简单地使用浏览器历史返回到前一页。如果之前没有导航发生过,我们可以告诉路由器直接进入我们的概览页面。第三个参数true告诉路由器用新的历史状态替换当前的历史状态,因为我们实际上是自己做反向导航的。第二个参数是一个空数组({}),因为我们没有将任何额外的参数传递给该路由。

对于我们的用例,这个实现比浏览器的back按钮要好一些。即使我们在应用程序之外的另一个页面上,浏览器也会回到历史的某一步。在app中,我们总是希望回到overview页面,即使我们来自另一个链接,或者直接用书签打开detail页面。你可以直接在一个新标签页加载细节页,然后点击应用程序中的back按钮,它仍然会回到overview页面。

Conventions

  当历史状态不清楚时,添加返回父页面的路径。

Parent topic: Walkthrough

Previous: Step 32: Routing with Parameters

Next: Step 34: Custom Controls

猜你喜欢

转载自www.cnblogs.com/ricoo/p/10103487.html