I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do “return” in $.ajax(…) success() function.
In this case i receive “undefined” instead of expected object. I understand, that the problem is in the “return” – it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?
window.DmnList = Backbone.Collection.extend({
model: DmnItem,
localStorage: new Store("hosting.WhoIs"),
destroyAll: function (options) {
while (this.models.length > 0) {
this.models[0].destroy(options);
}
},
getDomainZones: function(){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
success: function(data) {
console.log(data);
return data;//problem here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
});
Nowhere. You can’t return the result of an asynchronous AJAX request.
Any code that relies on the
data, must be called inside thesuccesscallback.One possibility is to have your
getDomainZonesmethod receive a function that will be called when the response is received.So then you’d pass a function to
getDomainZones, and when the response is received,getDomainZoneswill invoke the function you passed, passing it thedata.