I have a form that is being used to both create a new object and edit existing objects. The form contains a few plugins (date picker, jstree) and I'm trying to use jquery deferreds to make the loading cleaner. This is my first real attempt at using deferred objects.
What I want to do is firstly load the form, and then if I am editing an existing form, I also want to populate the form with the existing values. My cost looks like this (it's coffeescript, but I think its perfectly readable)
$.when(
# These functions all return jquery.Deferred objects.
getBookingDetails(id), buildJstree(), buildCalendar()
).then(
# Editing an existing booking
(bookingResponse, jstreeResponse_ignored, calendarResponse_ignored) =>
# ... populate form with data from bookingResponse ...
$("#name").val(bookingResponse[...])
# etc., Rest is omitted
).fail(
# Creating a new booking, so don't need to do anything more to the form.
() ->
)
So if I'm editing, I expect the $.when() to resolve and drop into the then(). If I am creating a new booking, I artificially cause the $.when() to fail like this
getBooking: (id) =>
if id is null
return $.Deferred().reject('id is null')
return $.ajax({
url : base + "/api/v1/daily/id/#{id}"
type : "GET"
contentType: "application/json"
data : {}
})
But I get the sense that this is wrong because if any of the other deferred objects in the $.when() fail, e.g. because my plugin didn't load correctly, then I will need to do extra work to check for this error, which just feels incorrect.
If my approach is indeed bad, can you explain to me why?
How do I restructure things to do this properly?