Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

JavaScript is the language everyone uses without bothering to learn it first, and I'm no exception. I'm trying to set up autorefresh with longpolling. What I have on the client side is the following:

var getAjaxer = function(element) {

    return function() {
        $.ajax({
            url: "/path/to/resource",
            success: function(response) {
                element.html(response);
            },
            dataType: "html",
            timeout: 10000,
            type: "POST",
            complete: arguments.callee
        });
    };
}

var startAjaxing = function() {
    myajaxer = getAjaxer($("#myid"));
    myajaxer();
}

$(startAjaxing);​

This works, but I'm worried I might be doing it all wrong. Could I get some pointers on how I could use the language more effectively?

share|improve this question

1 Answer

up vote 1 down vote accepted

I can't say whether yours is right or wrong but there were a couple of things that seemed odd to me.

I wouldn't add functions to variables unless you intend to use them more than once. (or it adds to the readability)

var startAjaxing = function() {
    myajaxer = getAjaxer($("#myid"));
    myajaxer();
}

$(startAjaxing);

then becomes:

$(function() {
    getAjaxer($("#myid"))();
}); // Start ajaxing

Also I would get rid of arguments.callee and get the element every time:

var getAjaxer = null;
getAjaxer = function(elementid) {
    return function() {
        $.ajax({
            url: "/path/to/resource",
            success: function(response) {
                $("#" + elementid).html(response);
            },
            dataType: "html",
            timeout: 10000,
            type: "POST",
            complete: getAjaxer(elementid);
        });
    };
}

To ME this seems easier to read butt it may be only a matter of taste. (PS. I didn't check this for syntax errors etc.)

If you don't want to create functions every time?

getAjaxer = function(elementid) {
    var elementAjaxer = $("#" + elementid).data("ajaxer");
    if(elementAjaxer == null){
        elementAjaxer = function() {
            $.ajax({
            // etc etc
            });
        };
        $("#" + elementid).data("ajaxer", elementAjaxer);
    }
    return elementAjaxer;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.