如何使用JSON文件和XML视图设置本地化数据绑定?

时间:2015-03-03 16:59:05

标签: javascript sapui5

我有一个包含一些图块的XMLView主页。这些切片是从JSON文件填充的。磁贴具有'title'属性,需要i18​​n数据绑定。

XML视图的一部分:

<TileContainer id="container" tiles="{/TileCollection}">
  <StandardTile
   icon="{icon}"
   title="{title}"
   press="onPress" />
</TileContainer>

JSON文件:

{
  "TileCollection" : [
      {
          "icon"   : "sap-icon://document-text",
          "title"  : "{i18n>foo}"
      }, 
      ... etc

我完成数据绑定的旧方法直接在title="{i18n>foo}"的视图中。当然,现在我基本上有两层数据绑定,一个用于i18n的JSON,另一个用于获取JSON(获取i18n)的视图。

这也是我设置i18n模型的Component.js。

sap.ui.core.UIComponent.extend("MYAPP.Component", {
  metadata: {
    rootView : "MYAPP.view.Home", //points to the default view

    config: {
      resourceBundle: "i18n/messageBundle.properties"
    },
    ... etc


  init: function(){
    sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
    var mConfig = this.getMetadata().getConfig();

    var oRouter = this.getRouter();
    this.RouteHandler = new sap.m.routing.RouteMatchedHandler(oRouter);
    oRouter.register("router");
    oRouter.initialize();

    var sRootPath = jQuery.sap.getModulePath("MYAPP");
    var i18nModel = new sap.ui.model.resource.ResourceModel({
        bundleUrl : [sRootPath, mConfig.resourceBundle].join("/")
    });
    this.setModel(i18nModel, "i18n");
}

这个问题源于对另一个问题的讨论,所以对于任何有兴趣的人可能会有更多的信息。 Link

1 个答案:

答案 0 :(得分:10)

我通常采用的方法是使用格式化程序函数,其唯一目的是为某个键获取正确的本地化值(在资源模型中维护,并由数据模型驱动)

例如,Tile UI看起来像这样:

<TileContainer id="container" tiles="{/tiles}">
    <StandardTile
      icon="{icon}"
      type="{type}"
      title="{ path : 'title', formatter : '.getI18nValue' }"
      info="{ path : 'info', formatter : '.getI18nValue' }"
      infoState="{infoState}" 
      press="handlePress"/>
</TileContainer>

(注意属性getI18nValuetitle的格式化程序函数info;这些是要翻译的属性。其他属性来自绑定的JSONModel)

该模型可能如下所示:

tiles : [
    {
        icon      : "sap-icon://inbox",
        number    : "12",
        title     : "inbox",   // i18n property 'inbox'
        info      : "overdue", // i18n property 'overdue'
        infoState : "Error"
    },
    {
        icon      : "sap-icon://calendar",
        number    : "3",
        title     : "calendar", // i18n property 'calendar'
        info      : "planned",  // i18n property 'planned'
        infoState : "Success"
    }
]

其中JSONModel的titleinfo属性值(例如,&#39;收件箱&#39;和#39;过期&#39;)与资源捆绑中的密钥对应文件(以及你的ResourceModel)

控制器中的格式化程序功能(或者更好,在独立的JS文件中,可以在多个视图中重复使用)非常简单:

getI18nValue : function(sKey) {
    return this.getView().getModel("i18n").getProperty(sKey);
}

它只是提供模型中的值(例如,&#39; inbox&#39;)并从资源模型中返回此键的本地化值