Problem
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?
Solution
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;
}