前面Step4 5 7包括8用到了MVC的概念,这一步用的是另一个很重要的结构组件Component。我们可以把UI assets装到一个index.html之外的一个独立的组件中,组件是可以被复用的,我们访问资源的时候就可以直接关系到这个组件而不是再关系到index.html。这种形式使APP更容易的被周围的Container使用,比如Fiori Launchpad。关注本文最后的run configuration
**webapp/Component.js **
sap.ui.define(
["sap/ui/core/UIComponent"],
function(UIComponent) {
"use strict";
return UIComponent.extend("", {
init: function() {
UIComponent.prototype.init.apply(this, arguments);
}
});
}
);
组件继承自基础class sap.ui.core.UIComponent,并且在重写的init方法里必须调用基础class的init函数。
然后在这个基础上加入上一节中的两个Model:
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");
}
});
});
可以看到这里主要加了两部分:
- metadata定义rootview。现在由Component来管理app view的显示。
- 之前在Controller介绍过的init函数,这个在Component组件被初始化时就会被调用。
当然init挪到Controller之后就要把Controller里的删掉,(记得把上面参考的路径也删掉)
** webapp/index.js **
sap.ui.define(
["sap/ui/core/mvc/XMLView"],
function(XMLView) {
"use strict";
sap.ui.getCore().attachInit(function () {
new sap.ui.core.ComponentContainer({
name : "Step9_Component"
}).placeAt("content");
});
/* XMLView.create({
viewName: "Step8_i18n.view.App"
}).then(function(oView){
oView.placeAt("content");
});*/
}
);
修改index.js,这时就不再实例化View了,而改为了现在的Component(跟着1.63.1的示例练习的同学倒霉了,因为官方材料漏了这部分)
sap.ui.core.ComponentContainer:
理解一下Component.js在整个应用中的位置就是这样的(因为图是之前画的,那时版本还没有index.js,所以在index.html和Component.js间还有一个index.js,实例component的动作是在index.js中完成的),index.html(或者index.js)只是一个Component Container,如果运行在fiori launchpad上,launchpad就是component Container
在加入component.js之后右键项目Run-Run Configurations,可以看到这里配置是可以执行component.js来运行应用,以来模拟在fiori launchpad中运行,此时其实是可以把index.html和index.js文件删除的
下图就是把index.html和index.js文件删除后执行component.js的效果,sk c
这个变化可以让我们更了解component.js的作用