It's been years since I've touched javascript and the strange scoping trips me up each time. Please could you point me into the right direction of how to both tidy this up and prevent the duplication?
It is simply two click events, with the only difference being the color updated on success.
$(function () {
$(".manualSubmitComplete")
.click(function () {
$(".spinner").show();
var $this = $(this);
$.get(this.href)
.done(function () {
var $parent = $this.parent();
$parent.children("spinner").show();
$parent.children("a").remove();
$parent.children("span").remove();
$parent.attr("class", "");
$parent.css("background-color", "#B0FFB0");
$(".spinner").hide();
});
return false;
});
$(".manualSubmitReject")
.click(function () {
$(".spinner").show();
var $this = $(this);
$.get(this.href)
.done(function () {
var $parent = $this.parent();
$parent.children("spinner").show();
$parent.children("a").remove();
$parent.children("span").remove();
$parent.attr("class", "");
$parent.css("background-color", "#FF0000");
$(".spinner").hide();
});
return false;
});
})
1 Answer 1
You can simply extract the common code into a function. Arguably you could pass this
rather than href
and $target
and derive ref and target in the function or pass $parent
rather than $target
, but the current arguments seem slightly clearer.
$(function() {
var fetchUrl = function (href, $target, color) {
$(".spinner").show();
$.get(href)
.done(function() {
var $parent = $target.parent();
$parent.children("spinner").show();
$parent.children("a").remove();
$parent.children("span").remove();
$parent.attr("class", "");
$parent.css("background-color", color);
$(".spinner").hide();
});
};
$(".manualSubmitComplete")
.click(function() {
fetchUrl(this.href, $(this), "#B0FFB0")
return false;
});
$(".manualSubmitReject")
.click(function() {
fetchUrl(this.href, $(this), "#FF0000")
return false;
});
});
manualSubmitComplete
andmanualSubmitReject
exist in the first place? I suspect that you may be doing something wrong, but I can't tell for sure from just this excerpt. A demo would be helpful; you can create on by pressing Ctrl-M in the question editor. \$\endgroup\$