Search code examples
performancedata-bindingsapui5

UI5 data binding via this.getOwnerComponent().getModel() or via this.getView().getModel()?


The common way to make a data binding in UI5 is via this.getView().getModel():

const wantedModel = this.getView().getModel("wantedModel");

this.getView().setModel(wantedModel);

However, it's possible to perform a binding via this.getOwnerComponent().getModel() as well:

const wantedModel = this.getOwnerComponent().getModel("wantedModel");

this.getView().setModel(wantedModel);

In my case, the data model is defined in manifest.json, and I have two options to retrieve a model for a binding:

  • via getView() in onBeforeRendering(), which is called every time a view is rendered
  • via getOwnerComponent() in onInit(), which is called only once.

To avoid setting a model every time a view is rendered, I consider using the second approach. What are the possible advantages/drawbacks, primarily performance-related, of getting a model via getOwnerComponent() over getView()?


Solution

  • In the base controller, from which all other controllers will be inherited, create a method like this:

    sap.ui.define([
        "sap/ui/core/Core"
    ], (Core) => Controller.extend("com.myapp.controller.BaseController", {
    
        getModel(sName) {
            const dataModel = this.getView().getModel(sName)
                                || this.getOwnerComponent().getModel(sName)
                                || Core.getModel(sName);
    
            return dataModel; 
        }
    }));
    

    Then put the base controller in your custom library and reuse it in the future.