mardi 18 août 2015

Refactor this javascript code snippet with module pattern

Here is a small code snippet I wrote. I feel like it's pretty naive. I copied the code directly from my project and renamed some id/class names. I wonder how you (advanced JS coders) could help to improve/refactor the code. radiobox1 and radiobox2 form a pair, and radiobox3 and radiobox4 form another pair - they're both mutually exclusive - which means select radiobox1 then radiobox2 is disabled, and vice versa. Then I will load the data in terms of the user's selection combination. In total, there are 4 selection combinations.

Thank you in advance!

var viz = (function () {
    var config = {
        width: 960,
        height:600,
        big: true,
        small: true,
        index: 0
    };

    var emptyGraph = function () {
        if (!$('#graph').is(':empty')) {
            $("#graph").empty();
        }
    };

    var bind = function () {
        $("#radiobox1").change(function () {
           if ($(this).is(':checked')) {
               emptyGraph();
               $("#radiobox2").prop("checked", false);
               config.small = true;
               loader.loadData(config);
           }
        });

        $("#radiobox2").change(function () {
            if ($(this).is(':checked')) {
                emptyGraph();
                $("#radiobox1").prop("checked", false);
                config.small = false;
                loader.loadData(config);

            }
        });

        $("#radiobox3").change(function () {
            if ($(this).is(':checked')) {
                emptyGraph();
                $("#radiobox4").prop("checked", false);
                config.big = true;
                loader.loadData(config);
            }
        });


        $("#radiobox4").change(function () {
            if ($(this).is(':checked')) {
                emptyGraph();
                $("#radiobox3").prop("checked", false);
                config.big = false;
                config.index = 1;
                loader.loadData(config);
            }
        });

    };

    return {
        init: bind,
    }

})();

Aucun commentaire:

Enregistrer un commentaire