Search code examples
sapui5

How to Reset Controls on Navigation


I have a UI5 app with three different pages.

  1. User inputs something on the first page, clicks a button and goes to the second page.
  2. There they press another button and go to the third page.
  3. There they can go back to previous pages.

The problem I have is that when trying to go back to a page for the second time, the onInit() function doesn't get called. It seems like the browser caches the data on the screen and does not reset the values as I want it to. I have to refresh the browser in order for that to work.

Here is my routing configuration:

routing: {
  config: {
    routerClass: "sap.m.routing.Router",
    viewPath: "BatchProcessing.view",
    controlId: "rootControl",
    controlAggregation: "pages",
    viewType: "XML"
  },
  routes: [
    {
      name: "page1",
      pattern: "",
      target: "page1"
    },
    {
      name: "page2",
      pattern: "Page2",
      target: "page2"
    },
    {
      name: "page3",
      pattern: "Page3",
      target: "page3"
    }
  ],
  targets: {
    page1: {
      viewName: "InputsView",
      viewLevel: 0
    },
    page2: {
      viewName: "TableView",
      viewLevel: 1
    },
    page3: {
      viewName: "DetailsView",
      viewLevel: 3
    }
  }
}

Here are the code snippets for the different controllers where I switch pages

controller 1

onToPage2 : function () {
  this.getOwnerComponent().getRouter().navTo("page2");
},

controller 2

onToPage1 : function () {
  // data = [];
  this.getOwnerComponent().getRouter().navTo("page1");
},

controller 3

onToPage2 : function () {
  this.getOwnerComponent().getRouter().navTo("page2");
},

Is there a way to update / clear the routing so when I go back to a page, everything is fresh?


Solution

  • Use attachRouteMatched()/attachRoutePatternMatched() methods of Router in your controller for resetting the data, e.g.:

    onInit: function() {
        sap.ui.core.UIComponent.getRouterFor(this)
            .attachRoutePatternMatched(this.onRouteMatched, this);
    },
    
    onRouteMatched: function(oEvent) {
        this.sRouteName = oEvent.getParameters().name;
        // Check route and reset your data
    }
    

    https://sapui5.hana.ondemand.com/#/api/sap.ui.core.routing.Router