Reputation: 5769
I used deferred to wait about two function to complete (they feed template and display the result) before feeding a select present in the template.
When a tab is displayed, i do.
var notAssociateContact = getNotAssociateContact();
var associateContact = getAssociateContact();
$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds\\[\\]]")));
function getNotAssociateContact() {
var deferred = $.ajax({
type: "GET",
url: "http://localhost:8080/rest/contacts/notassociatedto/" + $("#lodgerId").val(),
success: function(data, status, jqXHR) {
$("#lodgerContactAvailableDivTemplate").empty();
if (data.length != 0) {
$("#lodgerContactAvailableDivTemplate").append(templateLodgerContactAvailable(data));
$('#lodgerContactAvailableTableResult').bootstrapTable();
}
},
error: function(jqXHR, status) {
// error handler
alert("error " + jqXHR + " - " + status);
}
}).then(function(response) {
// optional callback to handle this response
});
return deferred;
}
function getAssociateContact() {
var deferred = $.ajax({
type: "GET",
url: "http://localhost:8080/rest/lodgers/" + $("#lodgerId").val() + "/contacts",
success: function(data, status, jqXHR) {
$("#lodgerContactDivTemplate").empty();
if (data.length != 0) {
$("#lodgerContactDivTemplate").append(templateLodgerContact(data));
$('#lodgerContactTableResult').bootstrapTable();
// $('#lodgerContactTableResult tr').bind("dblclick", null, contactReferenceSelectedRow);
}
},
error: function(jqXHR, status) {
// error handler
alert("error " + jqXHR + " - " + status);
}
}).then(function(response) {
// optional callback to handle this response
});
return deferred;
}
I don't get any error, but the assignLocationToSelector don't same to runned. Select is empty.
In console if i run
assignLocationToSelector($("select[name=locationIds\\[\\]]"));
Select is feeded correctly.
When i debug and arrive on $.when, i see then the two ajax call is pending...
So it's seem like there is a issue with the deferred.
Upvotes: 0
Views: 29
Reputation: 707786
Your $.when().then()
needs to be passed a function reference. You are calling a function immediately and then passing that return result. That executes the function immediately rather than allowing $.when()
to call it later.
Change your $.when()
statement from this:
$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds\\[\\]]")));
to this:
$.when(notAssociateContact, associateContact).then(function() {
assignLocationToSelector($("select[name=locationIds\\[\\]]"));
});
Upvotes: 2