Ad

How To Create An Instance Of The Model Class In MVC Pattern - SapUI5

- 1 answer

I am currently trying to implement the Model-View-Controller in my SAPUI5 / Fiori Project.

I managed to create an Instance of the Controller with: new sap.ui.core.mvc.Controller('controller.js')

This does not work for the Model (sap.ui.core.mvc does not contain a Model attribute).

Now I am searching a way to call functions of the Model from the Controller, to get my data.

I already tried this code: oObjModel = new sap.ui.mode.Model(), using this I cannot call functions from my Model.

Ad

Answer

I recommend you look at the walkthrough on the SAPUI5 documentation site. It shows how to initialize all the aspects of MVC in the correct way.


Models in SAPUI5 come in different classes to support different forms of data. For example, there is JSONModel, XMLModel, ODataModel, etc.

So to create a model, you need to first determine the specific type of model you need and use its specific constructor. For example, if you have JSON data (or simply a JavaScript object), you use the JSONModel:

var yourData = { "hello": "world" };
var oModel = new JSONModel(yourData);

Note that the above code assumes you are following the recommended way to use modules and that this code is wrapped with a sap.ui.define or sap.ui.require, where the module sap/ui/model/json/JSONModel is assigned to the variable JSONModel. The walkthrough shows this correct usage pattern. Accessing the constructor directly like the below is not recommended:

// Also probably works, but not the recommended way
var oModel = new sap.ui.model.json.JSONModel(yourData);

Your way of creating a controller is also not correct. You should preferably let the view instantiate the controller for you by providing it a controllerName, as shown in the walkthrough for Controllers.

<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc" controllerName="name.of.your.controller">
    <!-- ... -->
</mvc:View>

If you need to manually instantiate a controller from code, use this:

Controller.create({ name: "name.of.your.controller" }).then(function(oController) {
    // Do something with oController
});

This again assumes you have the module sap/ui/core/mvc/Controller linked to the variable Controller.

Before version 1.56, you can use the now-deprecated sap.ui.controller function to create controllers instead:

sap.ui.controller("name.of.your.controller", null, /*async=*/true).then(function(oController) {
    // Do something with oController
});

Be aware that both of these examples load the controller asynchonously, as synchronous XHR is being globally deprecated outside of Workers, and thus the framework recommends you to use async only. In fact, the new way of loading does not even provide an option for sync loading.

Ad
source: stackoverflow.com
Ad