SAP OPEN UI5 Step 9: Component Configuration

转载请联系vx:xiaoshitou5854

到目前,是用view替换的content(oView.placeAt("content");),view的定义,和view的实例化不在一个文件里;还有一个问题,在App.controller.js里实例化了Model,并把model设定到了view里。App.controller.js更应该控制页面的事件,所以应该把Model相关的代码拿出去,比较推荐的做法是,把view的定义和view使用到的model放到一起,也就是组件化。

webapp/Component.js (New)

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

      init : function () {
         // call the init function of the parent
         UIComponent.prototype.init.apply(this, arguments);
      }
   });
});

在init方法里,要先调用父类的init方法

webapp/Component.js

sap.ui.define([
   "sap/ui/core/UIComponent",
   "sap/ui/model/json/JSONModel",
   "sap/ui/model/resource/ResourceModel"
], function (UIComponent, JSONModel, ResourceModel) {
   "use strict";
   return UIComponent.extend("sap.ui.demo.walkthrough.Component", {
      metadata : {
         "rootView": {
            "viewName": "sap.ui.demo.walkthrough.view.App",
            "type": "XML",
            "async": true,
            "id": "app"
         }
      },
      init : function () {
         // call the init function of the parent
         UIComponent.prototype.init.apply(this, arguments);
         // set data model
         var oData = {
            recipient : {
               name : "World"
            }
         };
         var oModel = new JSONModel(oData);
         this.setModel(oModel);

         // set i18n model
         var i18nModel = new ResourceModel({
            bundleName: "sap.ui.demo.walkthrough.i18n.i18n"
         });
         this.setModel(i18nModel, "i18n");
      }
   });
});
  • 在UIComponent的构造方法里,使用metadata实例化view,实例化JSONModel,ResourceModel,以前要把Model放到view里,现在不用了,放到自己的里面就可以了。虽然没有放到view里,但也能从view里取得出来。

webapp/controller/App.controller.js

sap.ui.define([
   "sap/ui/core/mvc/Controller",
   "sap/m/MessageToast"
], function (Controller, MessageToast) {
   "use strict";
   return Controller.extend("sap.ui.demo.walkthrough.controller.App", {
      onShowHello : function () {
         // read msg from i18n model
         var oBundle = this.getView().getModel("i18n").getResourceBundle();
         var sRecipient = this.getView().getModel().getProperty("/recipient/name");
         var sMsg = oBundle.getText("helloMsg", [sRecipient]);
         // show message
         MessageToast.show(sMsg);
      }
   });
});

从controller里删除init方法

webappindex.js

sap.ui.define([
	"sap/ui/core/ComponentContainer"
], function (ComponentContainer) {
	"use strict";

	new ComponentContainer({
		name: "sap.ui.demo.walkthrough",
		settings : {
			id : "walkthrough"
		},
		async: true
	}).placeAt("content");
});

使用ComponentContainer替换view了。

本人微信:xiaoshitou5854

原文地址:https://www.cnblogs.com/xiaoshiwang/p/14920575.html