我在理解 this
的更改时遇到问题我的代码中的引用。所以我不明白三件事:
当我尝试将我的模型放入
onInit
时,我得到:"Cannot read property 'getProperty' of undefined".
但是我可以在 XML View 中访问 View 的模型,因为我在 manifest.json 中定义了模型,并在我的应用程序组件中使用了 list 。为什么我无法通过
this.getView().getModel
访问 Controller 中的模型?在我的
onDetailRouteHit
方法,我可以用this.getView().getModel
得到完美的模型.当我调用
_Test
时方法,我再次收到此错误:"Cannot read property 'getProperty' of undefined"
那么为什么我无法访问 onInit
中的模型但在 onDetailRouteHit
?为什么我可以在 onDetailRouteHit
中访问它但不在我之后调用的函数中?我习惯了Java,其中this
引用当前对象,我假设它是我的示例中当前所在的 Controller 。
this
有“规则”吗? JS/UI5 的范围?
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("test.controller.Detail", {
onInit: function() {
var array1 = this.getView().getModel("myData").getProperty("/myDataSet");
this.oRouter = this.getOwnerComponent().getRouter();
this.oRouter.getRoute("detail").attachPatternMatched(this._onDetailRouteHit.bind(this));
},
_onDetailRouteHit: function(oEvent) {
var array2 = this.getView().getModel("myData").getProperty("/myDataSet");
this._Test();
},
_Test: function() {
var array3 = this.getView().getModel("myData").getProperty("/myDataSet");
}
});
});
最佳答案
this.getView().getModel("myData")
在 onInit 中返回 undefined
是因为此时 View 尚未与父级关联。看看this graphic从文档中。它说:
Init function of controller is executed --> Router places views in root control: models are now available within the view and its controller.
如果您想从更高层次结构(例如组件模型)访问 onInit 中的模型,您需要显式获取该模型所有者的引用,然后从中调用 getModel
:this .getOwnerComponent().getModel("myData")
关于javascript - "this."对象引用 : Can't access model in onInit 范围的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022251/