3
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 14, 2012 at 15:05
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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;
}
answered Aug 15, 2012 at 6:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.