Skip to content

Instantly share code, notes, and snippets.

@Encosia
Created February 4, 2014 02:52
Show Gist options
  • Select an option

  • Save Encosia/8797427 to your computer and use it in GitHub Desktop.

Select an option

Save Encosia/8797427 to your computer and use it in GitHub Desktop.
I have a page that uses $.Deferred to simultaneously load data and its corresponding template, but the template that should be used depends on something rendered on the DOM. So, I need to wait until $(document).ready() to query that and load the appropriate template. Trying to figure out the cleanest way to return a promise out of the getTemplat…
var getTemplate = function() {
var dfd = $.Deferred();
// Need to wait on the DOM to be ready to determine which template to use.
$(document).ready(function() {
var conditionalThing = $('#some-selector').is('.foobar'),
templateUrl;
if (conditionalThing)
templateUrl = 'template1.htm';
else
templateUrl = 'template2.htm';
// Call the returned $.Deferred's resolve method with the $.get's result
// when the $.get completes.
$.get(templateUrl, dfd.resolve);
});
// Return this back so the calling code can tie it together with the data
// via $.when(data, template).
return dfd;
}
var data = $.getJSON('data.json'),
template = getTemplate();
$.when(data, template).done(function(data, template) {
// Render template with data here.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment