[js] jQuery plugin pattern
0
- 01.10.2011 (Събота)
(function($) {
$.pluginName = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {}
}
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
// code goes here
}
plugin.foo_public_method = function() {
// code goes here
}
var foo_private_method = function() {
// code goes here
}
plugin.init();
}
$.fn.pluginName = function(options) {
return this.each(function() {
if (undefined == $(this).data('pluginName')) {
var plugin = new $.pluginName(this, options);
$(this).data('pluginName', plugin);
}
});
}
})(jQuery);
като използването на плъгина става по следния начин:
// Инициализираме плъгина към даден елемент
$('#element').pluginName({'foo': 'bar'});
// извикваме публичен метод
$('#element').data('pluginName').foo_public_method();
// "взимаме" някоя от конфиг елементите
$('#element').data('pluginName').settings.foo;
Авторът е Stefan Gabos
Подобрена/обновена версия може да се изтегли от https://github.com/zenorocha/jquery-boilerplate/
