Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback in jQuery wrapper function

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();
    });
 }
like image 380
Jamie Carruthers Avatar asked Nov 14 '22 02:11

Jamie Carruthers


1 Answers

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 your success handler to avoid using a local variable:

function Bind(templateURL, templateData, templateTarget, callBack)
{
    $.get(templateURL).success(function(templateHtml) { 
        $(templateTarget).html($(templateHtml).tmpl(templateData));
        callBack();
    });
}

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, callBack will only be called on success, and without arguments.

like image 81
Frédéric Hamidi Avatar answered Dec 20 '22 00:12

Frédéric Hamidi