Implementing Module Pattern In Javascript With Dependency On Jquery
What is the best way to implement module pattern, while the module code depends on third party libraries like jQuery for example? var someModule = (function(){ //private attrib
Solution 1:
A great tutorial/example can be found here or here. I know this isn't the module pattern, but it offers the same benefits of the revealing module pattern along with allowing you to extend the namespace across files if needed. Below is the code from that example.
//Self-Executing Anonymous Func: Part 2 (Public & Private)
(function( skillet, $, undefined) {
//Private Propertyvar 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 MethodfunctionaddItem( item ) {
if ( item !== undefined ) {
console.log( "Adding " + $.trim(item) );
}
}
}( window.skillet = window.skillet || {}, jQuery ));
//Public Propertiesconsole.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 Propertyvar 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
}
Solution 2:
You can try something like this:
var someModule = (function($){
//private attributesvar privateVar = 5;
//private methodsvar privateMethod = function(){
return'Private Test';
};
return {
//public attributespublicVar: 10,
//public methodspublicMethod: function(){
return' Followed By Public Test ';
},
//let's access the private membersgetData: function(){
//make ajax call and do some processing and generate output
$.ajax( /* ... */ );
returnprivateMethod() + this.publicMethod() + privateVar;
}
}
})(jQuery); //the parens here cause the anonymous function to execute and return
someModule.getData();
Just make sure jQuery.js
is included before this code is executed.
Post a Comment for "Implementing Module Pattern In Javascript With Dependency On Jquery"