5
\$\begingroup\$

So I'm developing a webpage using MVC which will be mainly JavaScript driven.

Instead of using global variables, and global functions, I would like to do it right this time. I don't want to use something to complex, because the team and I are new to large JavaScript applications. I tried implementing the Module pattern to organize my functions and page state.

This is what I came up with so far.

Am I misusing the Module pattern? What am I doing wrong? Where will I get into trouble?

<script type="text/javascript">
    var ui = (function ($) {
        var _ui = {};

        _ui.submitMainForm = function () {                
            document.main.submit();
        };

        return _ui;
    } (jQuery));

    ui.tabs = (function ($) {
        var _tabs = {};

        var resourceTabs = $("#resourceTabs");
        var selectedTabPersistence = $("#SelectedTab");

        _tabs.getSelectedTab = function () {
            return selectedTabPersistence.val();
        };
        _tabs.setSelectedTab = function (value) {
            selectedTabPersistence.val(value);
        };
        _tabs.initialize = function () {
            resourceTabs.tabs({
                select: function (event, ui) { _tabs.setSelectedTab(ui.tab.hash); }
            });
            resourceTabs.tabs("select", _tabs.getSelectedTab());                
        };

        return _tabs;
    } (jQuery));

    ui.filter = (function ($) {
        var _filter = {};

        var personLevels = $("#personLevels");
        var vehicleLevels = $("#vehicleLevels");
        var personLevelsRadio = $("#personLevels :radio");
        var vehicleLevelsRadio = $("#vehicleLevels :radio");

        _filter.initialize = function () {
            personLevels.buttonset();
            vehicleLevels.buttonset();
            personLevelsRadio.bind("change", function () { ui.submitMainForm() });
            vehicleLevelsRadio.bind("change", function () { ui.submitMainForm() });
        };

        return _filter;
    } (jQuery));


    $(document).ready(function () {
        ui.tabs.initialize();
        ui.filter.initialize();
    });       
</script>
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You have multiple anonymous functions when you could do one and on the last line return your ui.* object.

var ui = (function($) {
    // local ui ref
    var ui = {};

    // other namespaces .. etc
    ui.tabs = {};

    return ui;
})(jQuery));
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.