Tuesday, June 5, 2012

JavaScript namespace



A lot of applications, such as Moodle LMS, YUI and the Dojo Toolkit use namespace in their JavaScript code. Namespace can  be used to mange JavaScript code and avoide conflict.

Example of namspace in Moodel LMS:
 Declare a name space M.mod_quiz.nav
M.mod_quiz.nav = M.mod_quiz.nav || {};
 Define a function  update_flag_state in namespace M.mod_quiz.nav
M.mod_quiz.nav.update_flag_state = function(attemptid, questionid, newstate) {
    var Y = M.mod_quiz.nav.Y;
    var navlink = Y.one('#quiznavbutton' + questionid);
    navlink.removeClass('flagged');
    if (newstate == 1) {
        navlink.addClass('flagged');
        navlink.one('.accesshide .flagstate').setContent(M.str.question.flagged);
    } else {
        navlink.one('.accesshide .flagstate').setContent('');
    }
};

Another way to define namespace:

var model = namespace(M.mod_quiz.nav);
model.update_flag_state = function(attemptid, questionid, newstate) {
 
}  
 
Reference:
 http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/

No comments:

Post a Comment