我正在尝试使用easyXDM覆盖主干模型获取函数,使用easyXDM的原因是因为服务器位于不同的域。
获取代码如下:
fetch: function(options)
{
model = this;
a = true;
this.xhr.request({
url: "http://server.dev:9000/users/" + this.id,
method: "GET"
}, function(response){
console.log(response.data);
var jsonResponse = JSON.parse(response.data);
if (jsonResponse.status == 'success'){
model.set({
firstName : jsonResponse.data.first_name,
lastName : jsonResponse.data.last_name,
email : jsonResponse.data.email,
companyName : jsonResponse.data.company.name,
companyId : jsonResponse.data.company.id
})
}
});
}下面是获取模型的控制器上的代码
var user = new UserModel({id : id});
user.fetch();
alert(user.get('firstName')); // display undefined所以问题是每当我调用fetch时,模型仍然没有被填充。我想是因为easyXDM请求是异步的,所以它还没有被填充。有没有什么方法可以确保模型已经填充好并可以使用了?可能是使用回调,有关于如何创建回调的指导吗?
发布于 2012-10-03 23:57:35
对不起,我一开始误解了你的问题。fetch是异步的,不管有没有easyXDM,所以你必须实现Fetch的onsuccess回调,或者在对模型进行任何操作之前检查是否设置了模型(使用length或其他方法)。这篇文章也可能会有所帮助:
Backbone.js: Elegant way to check if data ready and if the dataset is empty
https://stackoverflow.com/questions/12712262
复制相似问题