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.
}());

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: