I am trying to override backbone model fetch function using easyXDM, the reason for using easyXDM is because the server is located on different domain.
here is the fetch code:
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
})
}
});
}
And here is code on the controller fetching the model
var user = new UserModel({id : id});
user.fetch();
alert(user.get('firstName')); // display undefined
So the problem is whenever I call fetch, the model is still not populated yet.
I am thinking because the easyXDM request is async so its not yet populated.
Is there anyway to make sure that the model is populated and ready to use?
perhaps using a callback, any direction on how to create a callback?
Sorry, I misunderstood your question initially. Fetch is async with or without easyXDM, so you have to either implement the onsuccess callback of fetch, or check if the model is set (using length or other method) before doing any operations on it. This post may help as well:
Backbone.js: Elegant way to check if data ready and if the dataset is empty