Method onBeforeRendering not called

2019-08-08 16:58发布

问题:

I try to create a SAPUI5/OpenUI5 application. For that I use some XML-views and navigate between this with a router. Now, I want to call a method every time a specific view is opened. After reading that the method onBeforeRendering solves this case, I implement this function. When I navigate first time to the view the method was used, but not in the second call.

Here the code of the View-Controller:

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"],
function(Controller , JSONModel) {"use strict";

return Controller.extend("Spellcheck.controller.Result", {

    onBeforeRendering: function() {
        this.model = new sap.ui.model.json.JSONModel({
            suggestionData: []
        });
        this.getView().setModel(this.model);

       this.model.refresh();
       this.getCorrections();
    },

    getCorrections : function() {
      //...some other code...
    }

I hope someone know the reason and/or suitable solution for my problem

回答1:

It depends on the controls that you have around the view. More specifically, onBeforeRendering/onAfterRendering is called only when the DOM sub-tree needs to be completely regenerated (when the view's tree was removed previously from the DOM).

I would propose a different approach because the onBeforeRendering should generally be used for things related to the DOM / controls. For your specific use case, it would be better to listen on the patternMatched event of the route. This is the most common practice in UI5.

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel"
], function(Controller, JSONModel) {
"use strict";

return Controller.extend("Spellcheck.controller.Result", {
    onInit: function() {
        // It's better to use the JSONModel that you obtain from the 
        // enclosing function's parameters. This is because you are 
        // not using globals (so you are not coupled with globals). 
        // Also, you don't need to create a Controller property for the
        // model; you can always get it with this.getView().getModel().
        this.getView().setModel(new JSONModel({
            suggestionData: []
        }); 

        // Refreshing the model immediately after making it does
        // not do anything. You need to refresh it only if you 
        // change the data object from outside the model.
        // this.model.refresh(); 

        // Obtain the router, retrieve your route (replace myRoute
        // with your route's name) and then attach a listener
        // to the patternMatched event.   
        this.getOwnerComponent().getRouter().getRoute("myRoute")
           .attachPatternMatched(this.getCorrections, this);
    },

    getCorrections : function() {
      //...some other code...
    }
}


标签: sapui5