Реализация шаблона модуля в Javascript с зависимостью от JQuery - PullRequest
2 голосов
/ 03 января 2012

Каков наилучший способ реализации шаблона модуля, в то время как код модуля зависит от сторонних библиотек, таких как, например, jQuery?

var someModule = (function(){
    //private attributes
    var privateVar = 5;

    //private methods
    var privateMethod = function(){
        return 'Private Test';
    };

    return {
        //public attributes
        publicVar: 10,
        //public methods
        publicMethod: function(){
            return ' Followed By Public Test ';
        },

        //let's access the private members
        getData: function(){
            //make ajax call and do some processing and generate output
            return privateMethod() + this.publicMethod() + privateVar;
        }
    }
})(); //the parens here cause the anonymous function to execute and return

someModule.getData();

Мой вопрос: я планирую поместить весь код вбиблиотека как мода в файле javascript.

Как вы видите в методе getData(), я планирую делать вызовы ajax.Я хочу использовать библиотеку jQuery для этого.Теперь, как мне кодировать модуль javascript, полагаясь на jQuery?

Должен ли я вместо этого сделать всю мою библиотеку плагином jQuery?

Ответы [ 2 ]

1 голос
/ 04 января 2012

Отличный учебник / пример можно найти здесь или здесь . Я знаю, что это не шаблон модуля, но он предлагает те же преимущества, что и шаблон раскрывающегося модуля, и позволяет расширять пространство имен между файлами, если это необходимо. Ниже приведен код из этого примера.

//Self-Executing Anonymous Func: Part 2 (Public & Private)
(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }    
}( window.skillet = window.skillet || {}, jQuery ));

//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry(); //Adding Butter & Frying Bacon Strips

//Adding a Public Property
skillet.quantity = "12";
console.log( skillet.quantity ); //12

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " + 
                     skillet.ingredient + " & " + 
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
    };    
}( window.skillet = window.skillet || {}, jQuery ));

try {
    //12 Bacon Strips & 1 Cup of Grease
    skillet.toString(); //Throws Exception
} catch( e ) {
    console.log( e.message ); //isHot is not defined
}
0 голосов
/ 03 января 2012

Вы можете попробовать что-то вроде этого:

var someModule = (function($){
    //private attributes
    var privateVar = 5;

    //private methods
    var privateMethod = function(){
        return 'Private Test';
    };

    return {
        //public attributes
        publicVar: 10,
        //public methods
        publicMethod: function(){
          return ' Followed By Public Test ';
    },

    //let's access the private members
    getData: function(){
          //make ajax call and do some processing and generate output
          $.ajax( /* ... */ );
              return privateMethod() + this.publicMethod() + privateVar;
          }
     }
 })(jQuery); //the parens here cause the anonymous function to execute and return

someModule.getData();

Просто убедитесь, что jQuery.js включено до того, как этот код будет выполнен.

...