14-12-2009

jQuery plugin design pattern

The following design pattern was taken from Mike Alsup's article on the website learning jquery and serves as a handy starting point for scripting jquery plugins.

//
//create closure
//
(function($) {
	//
	// plugin definition
	//
	$.fn.hilight = function(options) {
	debug(this);
		// build main options before element iteration
		var opts = $.extend({}, $.fn.hilight.defaults, options);
		// iterate and reformat each matched element
		return this.each(function() {
			$this = $(this);
			// 	update element styles
			$this.css({
				backgroundColor: o.background,
				color: o.foreground
			});
			var markup = $this.html();
			// 	call our format function
			markup = $.fn.hilight.format(markup);
			$this.html(markup);
		});
	};
	//
	// private function for debugging
	//
	function debug($obj) {
		if (window.console && window.console.log)
			window.console.log('hilight selection count: ' + $obj.size());
	};
	//
	// define and expose our public format function
	//
	$.fn.hilight.format = function(txt) {
		return '<strong>' + txt + '</strong>';
	};
	//
	// plugin defaults
	//
	$.fn.hilight.defaults = {
		foreground: 'red',
		background: 'yellow'
	};
	//
	//end of closure
	//
})(jQuery);
 

Comments:

Your comment:

»

 

[x]