SAPUI5 JSONModel 扩展为单例实例

SAPUI5 JSONModel extended as singleton instance

我想知道是否可以创建一个扩展的 JSONModel 并将其作为单例实例。

我已经创建了我的扩展 JSONModel,但我需要在我的应用程序的不同部分使用它。

如何将模型的构造函数变为私有并创建 getInstance 方法?

感谢帮助!

如果您希望能够从任何地方访问您的模型,则不一定需要创建单例。例如,您可以创建模型实例并将它们分配给 UI5 核心。

// 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();

如果您坚持使用单例,则可以在创建实例后简单地删除构造函数:

(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;
    };
}());

这只是我的想法,所以可能会有错别字。

附带说明一下,我强烈建议阅读 What is so bad about singletons? 而不是使用它们,而是将模型注入到您的依赖项中。