如何将逻辑应用于绑定聚合以动态生成子项

How do I apply logic to binding aggregation in order to generate children dynamically

我在 SAPUI5 中有一个 table,它工作正常,显示 5 个单元格的信息。

但是,如何对此应用逻辑?例如,有时我需要第二个单元格是 sap.m.RatingIndicator 而不是 sap.m.Text.

有没有办法提供逻辑或必须始终对单元格进行硬编码?

oTable.bindItems("/", new ColumnListItem({
  cells: [
    new HTML({ // sap/ui/core/HTML
      content: "<p style='margin:0'>{path: 'Sequence', type: 'sap.ui.model.odata.type.String', constraints: {isDigitSequence: true}}.  {QuestionDesc} - <strong>{CompetencyDesc}</strong></p>"
    }),
    new Text({ // sap/m/Text
      text: "{AnswerLabel} ({AnswerScore})",
      visible: true
    }),
    new Image({ // sap/m/Image
      src: "{SmileyUrl}",
      width: "2em"
    }),
    // ...
  ]
}));

您可以使用工厂函数。

<Table items="{
  path: '/',
  factory: '.createColumnListItem'
}" />
createColumnListItem: function(id, context/*of the current item*/) {
  const displayRatingIndicatorInstead = /*...*/;
  return new ColumnListItem(id, {
    cells: [
      // ...
      displayRatingIndicatorInstead ? new RatingIndicator() : new Text(),
      // ...
    ]
  });
},

与提供模板控件相比,工厂函数允许我们为每个迭代步骤动态地实例化一个新控件。

有关更多信息和示例,请查看文档主题 Using Factory Functions


使用时bindItems

oTable.bindItems({
  path: "/",
  factory: this.createColumnListItem.bind(this),
  // no template!
  // ...
});

来自API reference: ManagedObject#bindAggregation

A factory function that will be called to create an object for each item in the aggregation; this is an alternative to providing a template object and can be used when the objects should differ depending on the binding context; the factory function will be called with two parameters:

  • An id that should be used for the created object, and
  • The binding context for which the object has to be created;

The function must return an object appropriate for the bound aggregation.