以下代码可以正常运行并完成我需要的一切,但它不是很干净。如果有人能指出更好的方法来完成我的任务,那将是非常棒的。我已经对代码进行了评论,以解释为什么我认为它会更好。
此代码为我的BuildingRoute定义了一个模型,并使用来自服务器的数据对其进行更新。
App.BuildingRoute = Ember.Route.extend({
buildingData : { // Can't I just create the object once my data comes,
name: '', // is it necessary to initialize this object?
addr1: '',
addr2: ''
},
model: function() {
this.getNodeInfo(); // should I be calling the function to access the server here?
return this.buildingData;
},
getNodeInfo: function(){
var _this = this;
var req = {
callback: nodeDataCB,
something: {
method: 'getNode',
uid: 'getNodeData',
nodeId: gVars.node
}
}
Server.getData(req);
function nodeDataCB(data){
console.log($.parseXML(data));
var attributes = $(data).find('attributes');
var addr1 = attributes.find('attr[n="disAddress1"]').html();
var addr2 = attributes.find('attr[n="disAddress2"]').html();
var name = $(data).find('name').text();
Ember.set(_this.buildingData, 'name', name); // must I set the value for each
Ember.set(_this.buildingData, 'addr1', addr1); // specifically, can't i just set
Ember.set(_this.buildingData, 'addr2', addr2); // the whole object at once?
}
}
});
我应该使用Ember数据吗?
答案 0 :(得分:1)
使用承诺。您可以处理服务器返回的数据,然后将最终数据传递给 resolve()。
App.BuildingRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.Promise(function(resolve) {
Server.getData({
something: {
method: 'getNode',
uid: 'getNodeData',
nodeId: gVars.node
},
callback: function(data) {
// your nodeDataCB here.
resolve(data);
});
});
}
});