jQuery Deferred and client-side templating - demo 1
See http://seewah.blogspot.co.uk/2012/10/jquery-deferred-and-client-side.html Handlebars.js Fancybox.js jQuery Deferred
by swc23
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
<link rel="stylesheet" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css">
<script src="http://fancyapps.com/fancybox/source/jquery.fancybox.js"></script>
<input type="button" id="show-modal" value="Show me the modal!">
JavaScript
var UI = {};
UI.Modal = (function() {
/**
* Shows waiting message
*/
function showWaitingMessage() {
showContent("Patience is a virtue...");
}
/**
* The main show content function.
* @param html the html to show
*/
function showContent(html) {
$.fancybox(html);
}
return {
showWaitingMessage: showWaitingMessage,
showContent: showContent
}
}());
UI.Templating = (function() {
/**
* Gets the html
* @param source template source
* @param data
* @return string the html
*/
function toHtml(source, data) {
var template = Handlebars.compile(source);
return template(data);
}
return {
toHtml: toHtml
}
}());
$("#show-modal").on("click", function(e) {
UI.Modal.showWaitingMessage();
// simulate template request
var dfdTpl = $.ajax({type: "POST",
url: "/echo/html/",
data: {html: "Hello from <b>{{name}}</b>!", delay: 1},
dataType: "html"
});
// simulate data request
var dfdData = $.ajax({type: "POST",
url: "/echo/json/",
data: {json: JSON.stringify({name: "See Wah"}), delay: 1},
dataType: "json"
});
$.when(dfdTpl, dfdData).done(function(arg1, arg2) {
UI.Modal.showContent(UI.Templating.toHtml(arg1[0], arg2[0]));
});
e.preventDefault();
});