本文介紹每次在 SAPUI5 中顯示視圖時如何執行方法。
有兩種方法可以實作這一點。
SAPUI5 提供了兩種每次調用視圖時執行代碼的方法:
視圖控制器中的生命周期鈎子
路由比對事件等路由機制
例如,調用自定義方法,或執行 CRUD 請求(建立、讀取、更新、删除)。
#1. SAPUI5 Life Cycle Hooks in a View’s Controller
onBeforeRendering:每次重新渲染視圖之前執行代碼。
onAfterRendering:每次渲染視圖時執行代碼。
除了 onBeforeRendering 和 onAfterRendering 生命周期鈎子之外,還有 onInit 和 onExit 鈎子。
另一方面,對于每個視圖執行個體,onBeforeRendering 和 onAfterRendering 鈎子隻調用一次:在執行個體化和銷毀視圖之後。
下面是如何在控制器中使用 onBeforeRendering 和 onAfterRendering 鈎子的示例:
// in your controller
...
// hook gets invoked before the view gets rendered
onBeforeRendering: function() {
this.log("view gets rendered);
},
// hook gets invoked after the view is rendered
onAfterRendering: function() {
this.log("view is rendered);
},
log: function(sMessage) {
sap.base.Log.info(sStatus);
}
...
#2. SAPUI5 Routing Mechanisms: Route Matched and Route Pattern Matched Events
如果您的應用程式使用 SAPUI5 路由架構,您可以利用其機制在每次調用視圖時調用您自己的代碼。
SAPUI5 URL 具有 URL 哈希。
例如,如果 URL 是 webapp/index.html#/products/3,則 URL 哈希是 #/products/3。
routeMatched 和 routePatternMatched 事件根據 manifest.json 中的路由設定檢查 URL 哈希。
每次 URL 哈希比對時,該事件都會被觸發。
每次導航到視圖及其 URL 時,都會觸發路由器事件。
為了更清楚地說明:
一方面,路由器事件檢查視圖的正确 URL 是否被調用,并且包括例如一個有效的參數,如對象 ID。
另一方面,隻要通過有效的路由 URL 調用視圖,就會觸發路由器事件。
下面是 routeMatched 和 routePatternMatched 事件之間的差別:
routeMatched:每次 URL 的哈希比對目前視圖的路由模式的任何路由、子路由或嵌套路由時調用。
routePatternMatched:每次 URL 的哈希與目前視圖的路由模式的路由比對時調用。
設定路由器事件需要兩個步驟:
在 SAPUI5 應用程式 manifest.json 中設定路由。
在 XML 視圖控制器中設定事件。
#1 Set Up Routing in the manifest.json
SAPUI5 應用程式的路由及其視圖的路由和模式在 manifest.json 中設定。
例如:
// in your manifest.json
...
"sap.ui5": {
...
"routing": {
"config": {
...
},
"routes": [{
"pattern": "",
"name": "Home",
"target": "home"
},
{
"pattern": "products",
"name": "Products",
"target": "products"
},
{
"pattern": "products/{productId}",
"name": "Product",
"target": "product"
}],
"targets": {
"home": {
"viewId": "home",
"viewName": "Home"
},
"employees": {
"viewId": "products",
"viewName": "Products"
},
"employee": {
"viewId": "product",
"viewName": "Product"
}
}
}
}
二、routePatternMatch 事件的例子:
// in the Product controller
// manifest.json routing pattern: products/{productId}
// URL: <your_app>#/products/product/<productId>
// URL hash: #/products/product/<productId>
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("my.app.controller.products.Product", function() {
onInit: function() {
var oRouter = this.getRouter();
// attach routePatternMatched event
oRouter.getRoute("product").attachRoutePatternMatched(this._onRoutePatternMatched, this);
},
_onRoutePatternMatched: function(oEvent) {
// gets called for ...#/products/Product/<productId>
// for example: ...#/products/Product/1
// or ...#/products/Product/123
}
});
});