我在我的Component.js中定义了两个模型。一个是所有联系人的列表,另一个是登录的联系人。现在,我想签入我的控制器,如果登录联系人已经存在于所有联系人的列表中。我将列表中的registrationToken与登录联系人中的令牌进行比较。但是当我循环遍历列表时,由于异步通信,长度是0。我看到了attachRequestCompleted函数,但现在我遇到了另一个问题.当我的附加函数填充我的视图-模型时,onInit-函数已经完成。
onInit : function(){
var gLocalContact = sap.ui.getCore().getModel("gLocalContact");
var gRemoteContacts = sap.ui.getCore().getModel("gRemoteContacts");
gRemoteContacts.attachRequestCompleted( function() {
... if ... setProperty to gLocalContact.getProperty("/registrationToken")...
console.log("I should be the first log to get the data in view");
});
console.log("I should be the second log!");
this.getView().setModel(gLocalContact, "localContact");
}
附件函数中的第一个日志应该是第一个,因为在那里,我为gLocalContact定义了一些数据,我认为这是我所需要的。另一个问题是我无法访问我的gLocalContact变量.
发布于 2016-02-04 22:39:11
这有点难看,因为SAPUI5不支持承诺。因此,在您的视图中,您不知道requestCompleted事件是否会被触发,或者数据是否已经加载。我想到了一些解决办法:
onInit : function(){
var gLocalContact = sap.ui.getCore().getModel("gLocalContact");
var gRemoteContacts = sap.ui.getCore().getModel("gRemoteContacts");
console.log("Wait some seconds for the data...");
var localContactPromise = this.getPromise(gLocalContact, "/origin");
localContactPromise.done(function() {
//same code as before but this time you can be shure its called.
//... if ... setProperty to
//gLocalContact.getProperty("/registrationToken")...
console.log("I should be the first log to get the data in view");
});
var remoteContactsPromise = this.getPromise(gRemoteContacts,"/origin"); //Wait for the other model to
$.when(localContactPromise, remoteContactsPromise).done(function(){
//When both models are loaded do this
console.log("I should be the second log!");
this.getView().setModel(gLocalContact, "localContact");
this.byId("label").setText("all loaded");
}.bind(this));
},
getPromise:function(oModel, pathToTestForData){
var deferred = $.Deferred();
if (oModel.getProperty(pathToTestForData))
deferred.resolve(); //Data already loaded
else
oModel.attachRequestCompleted(deferred.resolve); //Waiting for the event
return deferred.promise();
}
Promise
是一个具有已完成事件的对象。Deferred
是一个具有Promise
和resolve()
方法的对象,它将根据承诺引发已完成的事件。如果您首先在延迟上调用resolve()
,然后为done
注册一个处理程序,则会立即调用该处理程序。因此,即使您比异步加载请求慢,也不会错过该事件。
但是:如果当您的视图初始化时,您的模型甚至无法在组件/核心上设置,那么您就有一个严重的问题,因为不存在modelChanged事件。我建议创建一个空模型,并将其分配给组件init方法中的组件,然后在该模型上使用loadData()
。
https://stackoverflow.com/questions/35202170
复制相似问题