sapui5

Why Is My Main Controller Being Called Twice?


All other routings are fine, but for some reason the main controller is being called twice. Why would this happen?

onInit: function() {
  var oRouter = this.getOwnerComponent().getRouter();
  oRouter.getRoute("main").attachMatched(this._onRouteMatched, this);
  this.getView().setModel(new JSONModel({
    Jobs: []
  }), "job");
},

Is this down to the routing config?

"rootView": {
  "viewName": "CompleteSurvey.view.Main",
  "type": "XML"
},
"routing": {
  "routes": [{
    "name": "main",
    "pattern": "",
    "target": ["main"]
  }],
  "config": {
    "routerClass": "sap.m.routing.Router",
    "viewType": "XML",
    "viewPath": "CompleteSurvey.view",
    "controlId": "app",
    "controlAggregation": "pages"
  },
  "targets": {
    "main": {
      "viewName": "Main"
    }
  }
}

Solution

  • The reason why your Main controller is created twice is because its view is created twice.

    1. The framework fetches manifest.json and looks at the /sap.ui5/rootView/viewName value to create the assigned view ("CompleteSurvey.view.Main").
    2. The Router gets initialized, typically in the Component controller (Component.js), sees that the current hash or pattern is "", and creates the corresponding view which is the "Main" view again.

    The current best practice is to have a separate root view. You can keep the Main for the "" pattern, but avoid using the same view again as a root view.

    For further references, take a look at the tutorial Navigation and Routing and this answer.


    Another typical reason is the Component itself being created twice with the same name.