Good day, I wrote a simple gallery script , since I just started to study JS normally, I’m sure that there is a lot of rubbish in the code, if you have time, take a look, criticism and nose-poking at mistakes is welcome! thank!
- oneI don’t like the checkButtons function aesthetically, well, if you did it in the form of a plugin, it would be more compact and simpler. - zb '
- Eicto, thanks, I’ll dig if I thought how to organize it in a plugin, I would hardly have asked this question! Now I will look for mana by writing plugins! - Cone
- some other bugs with the display of buttons, if you open / close. - zb '
- I did an example of a gallery here, I don’t remember why jsfiddle.net/oceog/R9kcN - zb '
- Bugs with the display of buttons removed! jsfiddle.net/Cone/xw63k/1 - Cone
|
2 answers
If you want to make jQuery plugin, I can share the workpiece that I wrote for myself. I added comments to make it more clear what and why.
; (function ($, undefined) { // Название плагина; также имя функции для подключения $(selector).myPlugin( ... ) var pluginName = 'myPlugin', // Стандартные опции defaults = { optionOne: false, message: 'no message set' }; /// Конструктор /// element : $, options : {} function MyPlugin(element, options) { // Сохраняем элемент для последующего использования this.element = element; // Установка опций // Комбинируем стандарты + пользовательские опции this.options = $.extend({}, defaults, options); // Инициализация плагина this.init(); } MyPlugin.prototype = { // Пример обработчика событий _onClick: function (e) { // Для доступа к объекту плагина: // var plugin = $(this).data(pluginName); alert(pluginName + ' - click - ') }, init: function () { // Добавляем обработчик событий this.element.on('click', this._onClick); }, test: function(username, message) { alert("Dear " + username + ":\n" + message); }, // Функция удаления плагина destroy: function () { // Снимаем обработчик событий this.element.off('click', this._onClick) // Удаляем объект плагина из data элемента. .removeData(pluginName); } }; // Делаем плагин доступным для всех объектов jQuery // Функция обработки элементов к которым нужно подключить плагин $.fn[pluginName] = function (options) { // Кэшируем аргументы функции var args = arguments; // Обрабатываем все элементы return this.each(function () { // Проверяем подключен ли плагин к актуальному элементу // Если да, то options это название функции которую нужно вызвать, // а args аргумент для этой функции var cached = $.data(this, pluginName); if (cached) { if(options.substring) cached[options].apply(cached, [].splice.call(args, 1)); return true; } // Если плагин не подключен, и идет вызов функции // кидаем исключение else if(options.substring) throw new Error(pluginName + ' не создан для данного элемента'); // Иначе оборачиваем элемент в объект jQuery cached = $(this); // Создаем плагин и сохраняем его в data элемента cached.data(pluginName, new MyPlugin(cached, options)); }); }; })(jQuery); /* Использование: * * Создание плагина: * * $(selector).myPlugin({ message: 'Новый плагин' }); * * Вызов функции: * * $(selector).myPlugin('test', 'Вася', 'Тестовое сообщение'); * * Удаление плагина: * * $(selector).myPlugin('destroy'); * */
Demonstration: http://jsfiddle.net/pbuuy/
If there are any shortcomings, I will be glad to hear.
- Pavel, thank you! Now I will look, pick! I hope something sensible will come out !! - Cone
|
Take better than any of the existing ones. Why reinvent the wheel?
- Ready to take a lot of mind is not necessary, until you suffer nothing you learn. - Cone
- Again, it's easier to take a ready-made gallery and see how it is implemented. - alekseidolganov
|