OpenUI5:组件中的访问模型

OpenUI5: Access model in component

我有一个代表 Web 应用程序的组件:

sap.ui.define( ["sap/ui/core/UIComponent"], function (UIComponent) {
"use strict";
return UIComponent.extend("dividendgrowthtools.Component", {

    metadata: ...
    init : function () {

        UIComponent.prototype.init.apply(this, arguments);

        ...

        // set i18n model
        ...
        var i18nModel = new sap.ui.model.resource.ResourceModel({
                            bundleUrl: [rootPath, mConfig.resourceBundle].join("/"),
                            bundleLocale: sCurrentLocale });

        this.setModel(i18nModel, "i18n");

        // redirect the "dividendgrowthtools" package to the local web app
        jQuery.sap.registerModulePath("dividendgrowthtools", "/");

        }

});
}, /* bExport= */ true);

在该组件中我设置了 i18n 模型。

此外,我有一个帮助对象,我想用它来切换应用程序的语言:

jQuery.sap.require("jquery.sap.resources");

jQuery.sap.declare("dividendgrowthtools.util.Helper");

Helper = {
    ...

    switchLanguage: function(sLocale) {

    // set new locale
    sap.ui.getCore().getConfiguration().setLanguage(sLocale);

    // load and set new ressource bundle
    var rootPath = jQuery.sap.getModulePath("dividendgrowthtools");

    var i18nModel = new sap.ui.model.resource.ResourceModel({
                            bundleUrl: [rootPath, "i18n/messageBundle.properties"].join("/"),
                            bundleLocale: sLocale
        });

    // does not work as it's not the component model (set to core)
    sap.ui.getCore().setModel(i18nModel, "i18n");

...

我的想法是加载并设置一个新的 i18n 模型。问题是,我找不到分别访问组件的可能性,我在组件的 init 方法中设置的 i18n 模型。

有人知道如何请求组件引用或如何访问组件中的模型集吗?

最简单的方法是从调用控制器传递控制器对象。您会将您的 Helper 函数更改为 sth。像这样:

switchLanguage(sLocale, oController): function() {
   var oComponent = oController.getOwnerComponent();
   ...
}

然后您可以从您的控制器函数中调用该方法,如下所示:

callMyHelperFunction: function() {
   Helper.switchLanguage("en", this);
}

我找到的另一个解决方案如下:

  1. 像这样创建组件(以确保组件获得一个好的 id):

            // create component
            var oMainComponent = sap.ui.getCore().createComponent({
                 name: "dividendgrowthtools",
                 id: "maincomponent"
            });
    
            // create and place component container
            var oComponentContainer = new sap.ui.core.ComponentContainer("componentcontainer", {
                     component: oMainComponent
            });
            oComponentContainer.placeAt("content");
    
  2. 通过 Helper 对象中的 ID 获取组件引用并设置新模型:

    var oComponent = sap.ui.getCore().getComponent("maincomponent"); 
    oComponent.setModel(i18nModel, "i18n");