0

I'd like to know if is possible to create a JSONModel extended and make it as singleton instance.

I've already created my extended JSONModel but I need to use it in different parts of my app.

How to turn the constructor of my model private and create the getInstance method?

Thanks for help!

Marin Todorov
  • 6,377
  • 9
  • 45
  • 73
mayconbelfort
  • 195
  • 1
  • 5
  • 17

1 Answers1

2

If you want to be able to access your model from anywhere, you don't necessarily need to create a singleton. You could for example create the model instance and assign them to the UI5 Core.

// Where you create your model
var oModel = new CustomModel();
sap.ui.getCore().setModel(oModel);

// To access the model from anywhere
var oModel = sap.ui.getCore().getModel();

If you insist on having a singleton, you could simply remove the constructor once the instance has been created:

(function() {
    "use strict";
    var oInstance;
    sap.ui.model.json.JSONModel.extend("CustomModel", {
        constructor : function() {
            sap.ui.model.json.JSONModel.apply(this, arguments);
            if (oInstance) {
                throw "Constructor of singleton cannot be called"
            }
        }
    });
    CustomModel.getInstance = function() {
        if (!oInstance) {
            oInstance = new CustomModel();
            oInstance.constructor = null
        }
        return oInstance;
    };
}());

That's just from the top of my head so there might by typos in there.

On a side note, I would highly recommend reading What is so bad about singletons? and instead of using them, rather inject the model to your dependencies.

Community
  • 1
  • 1
mlenkeit
  • 211
  • 1
  • 4