SAPUI5基础知识24 - 如何向manifest.json中添加模型(小结)
1. 背景
在上一篇博客中,我们总结了SAPUI5中模型的各种类型,并通过代码给出了实例化这些模型的方式。
其实,在SAPUI5中,我们可以通过在manifest.json
中添加模型配置,简化模型的初始化过程,并确保模型在应用程序启动时自动加载。
这样,就省去了手动实例化模型的动作,可以简化我们的程序设计逻辑。
2. 示例
2.1 定义数据源
首先,需要在 manifest.json
中定义数据源"dataSources"
。数据源可以是 OData
服务、JSON
文件等。
{"sap.app": {"id": "my.namespace","type": "application","i18n": "i18n/i18n.properties","dataSources": {"mainService": {"uri": "/path/to/odata/service/","type": "OData","settings": {"odataVersion": "2.0"}},"localData": {"uri": "model/localData.json","type": "JSON"}}}
}
2.2 关联数据源
接下来,需要在 manifest.json
中的 sap.ui5
节点下,定义模型并关联到数据源。
{"sap.ui5": {"models": {"": {"dataSource": "mainService","settings": {"defaultBindingMode": "TwoWay"}},"local": {"type": "sap.ui.model.json.JSONModel","uri": "model/localData.json","settings": {"defaultBindingMode": "OneWay"}},"i18n": {"type": "sap.ui.model.resource.ResourceModel","settings": {"bundleName": "my.namespace.i18n.i18n"}},"device": {"type": "sap.ui.model.json.JSONModel","settings": {"defaultBindingMode": "OneWay","data": {"isPhone": "{device>/system/phone}","isTablet": "{device>/system/tablet}"}}}}}
}
2.3 组件配置
完成上面的步骤后,需要在 Component.js
中,确保调用父类的 init
方法,这样模型会根据 manifest.json
中的配置自动初始化。
sap.ui.define(["sap/ui/core/UIComponent","sap/ui/Device"
], function (UIComponent, Device) {"use strict";return UIComponent.extend("my.namespace.Component", {metadata: {manifest: "json"},init: function () {// 调用父类的 init 函数UIComponent.prototype.init.apply(this, arguments);// 设置设备模型var oDeviceModel = new sap.ui.model.json.JSONModel(Device);oDeviceModel.setDefaultBindingMode("OneWay");this.setModel(oDeviceModel, "device");}});
});
2.4 数据绑定
通过以上步骤,就完成了模型的自动初始化。这样,在视图中,就可以通过数据绑定来直接使用这些模型了。例如:
<mvc:ViewcontrollerName="my.namespace.controller.Main"xmlns:mvc="sap.ui.core.mvc"xmlns="sap.m"><Page title="{i18n>title}"><content><Text text="{/name}" /><Text text="{local>/address/street}" /><Text text="{device>/isPhone}" /></content></Page>
</mvc:View>
4. 小结
本文总结了向manifest.json
中添加模型的方式,并给出了具体的代码示例。