Extending jQuery

@boulderux

#boulderuxmeetup

What you need

The Basics

Closure

(function($){
	//plugin code
})(jQuery);

How to extend the jQuery object

(function($){
	//plugin code
	$.fn.myPlugin = $.myPlugin = function(){
		//this is the plugin constructor
	};
})(jQuery);

Maintaining method chaining

(function($){
	//plugin code
	$.fn.myPlugin = $.myPlugin = function(){
		//this is the plugin constructor
		//return the instance of the jQuery object
		return this;
	};
})(jQuery);

Add some methods

(function($){
	//plugin code
	$.fn.myPlugin = $.myPlugin = function(params){
		//this is the plugin constructor
		
		//new method
		this.pink = function(){
			return this.each(function(){
				$(this).css({'color':'pink'});
			});
		};
		
		return this;
	}; 
})(jQuery);

Better Code Structure

(function($){
	//plugin code
	$.fn.myPlugin = $.myPlugin = function(params){
		//this is the plugin constructor
		//each instance of the plugin gets its own
		//instance of the public methods
		var methods = new PublicMethods(params);
		var self = $.extend({},this,methods);
				
		//return jQuery to maintain chaining
		return self;
	};
	//methods are public because we extend 
	//jQuery in the constructor
	var PublicMethods = function(){};
	
	PublicMethods.prototype.pink = function(){
		//return the "this" keyword for chainability
		return this.each(function(){
			$(this).css({'color':'pink'});
		});
	}; 
})(jQuery);

Extending jQuery

@boulderux

#boulderuxmeetup