티스토리 뷰

웹개발/Jquery

jQuery 모듈 패턴

yaku 2011. 8. 12. 17:52

//네임스페이 정의
if (typeof (CompanyName) === 'undefined') {
    CompanyName = {};
}


//네임스페이스 App이름
CompanyName.AppName = (function ($) {

    //  변수의 연속 선언
    var _first = function () {
        // Important to always start with "var"
    },

    _second = function () {
        // Chained (  ...},  ) so it doesnt need "var"
    },

    _third = "Just a var", // Variables just ends with ,

    _four = "Another var"; // Closing the chain with ;

    var _anotherFirst = function () {
        // Previous chain of var's was ended with ; so this var needed "var" in order to start.
    };

    g_globalVar = "I'm free!"; // 전역 변수 .. 어디서든 동작

    g_globalMethod = function () {
        alert("I'm free too!"); // 전역 함수 .. 어디서든 동작
    };

    g_chainedGlobalVarOne = "We are free!",
    g_chainedGlobalVarTwo = "We are free!";

    // private 변수 .
    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";

    // private 메서드.
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {
            // Calling private
            _privateMethod();

            // Calling Public
            this.myPublicMethod();

            // Also Calling Public
            CompanyName.AppName.myPublicMethod();

            // Calling Other namespace's Public Method (when exists)
            //CompanyName.OtherNamespace.externalPublicMethod();
        },

        // Public
        myPublicMethod: function() {
            log("myPublicMethod");
        },
        // In a View (MVC), I could have a page called myPage where I want to init
        // some particular functions. myPage can be called just like init.
        myPage: function() {
            _second();
            _third();
        }

    }
})(jQuery);

// Initialize
jQuery().ready(function() {
    CompanyName.AppName.init()
    CompanyName.AppName.myPublicMethod();
});

댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함