patternjavascriptMinor
Simplifying a repetitive event handler
Viewed 0 times
repetitivehandlersimplifyingevent
Problem
Is there a more efficient way of writing this? It seems like so much redundancy that this can be greatly reduced. Basically the only difference is if
isNodeWebkit is true then run a function using key code 113 or 112if (isNodeWebkit) {
$(document).keyup(function (e) {
if (e.which == 113) {
$.ajax({
type: "POST",
url: "/submit/role/",
data: {},
dataType: "json",
success: function (admin) {
if (admin == true) {
window.location = urllink;
}
}
});
};
});
}
else {
$(document).keyup(function (e) {
if (e.which == 112) {
$.ajax({
type: "POST",
url: "/submit/role/",
data: {},
dataType: "json",
success: function (admin) {
if (admin == true) {
window.location = urllink;
}
}
});
};
});
};Solution
Yes! Introduce a
Edit: Reverted equality tests since I don't know what you expect to appear in
keyCode variable to hold the one difference between the two otherwise identical code blocks.var keyCode = isNodeWebkit ? 113 : 112;
$(document).keyup(function (e) {
if (e.which == keyCode) {
$.ajax({
type: "POST",
url: "/submit/role/",
data: {},
dataType: "json",
success: function (admin) {
if (admin == true) {
window.location = urllink;
}
}
});
};
});Edit: Reverted equality tests since I don't know what you expect to appear in
admin, and heck, perhaps some browsers convert the key code to a string!Code Snippets
var keyCode = isNodeWebkit ? 113 : 112;
$(document).keyup(function (e) {
if (e.which == keyCode) {
$.ajax({
type: "POST",
url: "/submit/role/",
data: {},
dataType: "json",
success: function (admin) {
if (admin == true) {
window.location = urllink;
}
}
});
};
});Context
StackExchange Code Review Q#51163, answer score: 9
Revisions (0)
No revisions yet.