JSONModel 更改的事件处理程序?

Event Handler for JSONModel Change?

比如说,有一个 sap.m.table 的项目绑定到 JSON 模型 - “/rows”。在 sap.m.table 布局之外,有一个包含 "Add" 按钮的工具栏,用于向 table 添加行。 "Add" 按钮使用模型的 setProperty 方法将行添加到 table。现在,要求是当 JSON 模型“/rows”长度达到 10 时禁用 "Add" 按钮。我们如何创建一个处理程序来观察 JSON 模型的“/rows”的变化属性? https://sapui5.netweaver.ondemand.com/1.52.22/#/api/sap.ui.model.Model/events/propertyChange 表示 目前事件仅在 sap.ui.model.ChangeReason.Binding 的情况下触发,当 属性 绑定的值发生双向变化时触发。 这意味着当调用 JSONModel 的 setProperty() 时,不会触发 属性Change 的事件处理程序。有没有办法让我们可以观察到 JSONModel 的 属性 变化 - 在这种情况下,JSONModel 的“/rows”属性?

好吧,我可以想出几种方法来实现这个

1。标准视图绑定 + 格式化程序:

查看

...
<Button text="Add" press="onPressAdd" enabled="{path: '/rows', formatter: '.isAddEnabled'}" />
...

控制器:

Controller.prototype.isAddEnabled = function(rows) {
    return rows && rows.length < 10;
}

2。表达式绑定(纯xml)

...
<Button text="Add" press="onPressAdd" enabled="{= ${/rows/length} &lt; 10 }" />
...

3。 JSONPropertyBinding(纯javascript)

您可以在 JSONModel 上调用 bindProperty 来创建可以观察到更改的 属性 绑定:

https://sapui5.hana.ondemand.com/#/api/sap.ui.model.Model/methods/bindProperty https://sapui5.hana.ondemand.com/#/api/sap.ui.model.json.JSONPropertyBinding

Controller.prototype.onInit = function() {
    var model = this.getMyJsonModel();
    var button = this.getView().byId("myButtonId");

    model.bindProperty("/rows").attachChange(function(event) {
        button.setEnabled(event.getSource().getValue().length < 10);
    })
}