HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Simplifying a repetitive event handler

Submitted by: @import:stackexchange-codereview··
0
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 112

if (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 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.