I have written a function that retrieves a html template, then binds data using jQuery.tmpl. I think it’s fairly neat and tidy and encapsulates what I need and provides me a reusable function. My question however is can it be improved.
My main concern is what if the $.get method fails, and also how the callBack function is executed.
function Bind(templateURL, templateData, templateTarget, callBack){
var req = $.get(templateURL);
req.success(function(templateHtml) {
$(templateTarget).html(''); //clear
$(templateHtml).tmpl(templateData).appendTo(templateTarget); //add deal
callBack();
});
}
You can pass the result of
tmpl()directly to html() to clear your target container and append the new content at the same time. You can also chain the result of $.get() into yoursuccesshandler to avoid using a local variable:If
$.get()fails, nothing will happen since you do not register an error handler. What that handler would do is up to you, but you might want to display an appropriate message in an alert box or somewhere on the page.Your second concern is less clear. As it stands,
callBackwill only be called on success, and without arguments.