a developer's notes – a semi-technical web development BLOG

May 13, 2015

Javascript Namespace Function Expression Sample

Filed under: Javascript / JQuery — Duy Nguyen @ 12:05 pm
Tags: , ,

A sample of how to structure your JS file per page. This works good for organizational purposes and it will avoid name clashing.

var PageName = {

// define your functions as variables.
    bindCheckBox: function () {
        $("#mycheckbox").on("click", function () {
            PageName.checkboxClick();
        });
    },

    enableConfirmButton: function (bool) {
        if (bool)
            $("#mybutton").removeAttr("disabled");
        else
            $("#mybutton").attr("disabled", "disabled");
    },

    checkboxClick: function () {
        if ($("#mycheckbox").is(":checked"))
            this.enableConfirmButton(true);
        else
            this.enableConfirmButton(false);
    }
}

// Start of document.ready in jquery
$(function () {
    // calling the global variable you created.
    PageName.bindCheckBox();
});

If you want to use an Immediately Invoked Function Expression (IIFE)


(function() {
     // This creates a function that invokes itself with NO GLOBAL FUNCTIONS.
}());

Create a free website or blog at WordPress.com.