patternjavascriptMinor
Sending Ajax requests and updating DOM
Viewed 0 times
ajaxupdatingsendingdomrequestsand
Problem
I wrote some ugly JavaScript that is responsible for sending Ajax requests and update the DOM. I'm using it to show user progress of background jobs.
What can I refactor in this code to make it better?
this.AjaxPoller = {
poll: function() {
setTimeout(this.AjaxPoller.request, 5000);
},
request: function() {
$(".ajax_poller[data-url]").each(function(i, elem) {
url = $(elem).data("url");
$.getJSON(url, function(data) {
if (checkProgress(data)) {
location.reload();
};
$.each(data, function( key, val ) {
$(key+ ' .progress_info').html(val);
$(key + ' .progress-bar').width(val);
});
});
});
}
};
var checkProgress = function(obj) {
correct = true;
for (key in obj) {
if (obj[key] != '100%') correct = false;
}
return correct;
}What can I refactor in this code to make it better?
Solution
I personally like to rely on named functions rather than inline anonymous functions.
this.AjaxPoller = {
poll: poll,
request: request
};
function request() {
$(".ajax_poller[data-url]").each(fetchDataForElement);
}
function fetchDataForElement(i, elem) {
var url = $(elem).data("url");
$.getJSON(url, handleJson);
}
function handleJson(data) {
if (checkProgress(data)) {
location.reload();
}
$.each(data, function(key, val) {
$(key+ ' .progress_info').html(val);
$(key + ' .progress-bar').width(val);
});
}
function poll() {
setTimeout(this.request, 5000);
}
function checkProgress(obj) {
var correct = true;
for (key in obj) {
if (obj[key] != '100%') correct = false;
}
return correct;
}Code Snippets
this.AjaxPoller = {
poll: poll,
request: request
};
function request() {
$(".ajax_poller[data-url]").each(fetchDataForElement);
}
function fetchDataForElement(i, elem) {
var url = $(elem).data("url");
$.getJSON(url, handleJson);
}
function handleJson(data) {
if (checkProgress(data)) {
location.reload();
}
$.each(data, function(key, val) {
$(key+ ' .progress_info').html(val);
$(key + ' .progress-bar').width(val);
});
}
function poll() {
setTimeout(this.request, 5000);
}
function checkProgress(obj) {
var correct = true;
for (key in obj) {
if (obj[key] != '100%') correct = false;
}
return correct;
}Context
StackExchange Code Review Q#93741, answer score: 3
Revisions (0)
No revisions yet.