Хочу научиться создавать плагины JQuery — с чего начать?

Хочу научиться создавать плагины JQuery - с чего начать?
  • Вопрос задан
  • 3542 просмотра
Решения вопроса 4
dunmaksim
@dunmaksim
Технический писатель
Чтобы создавать свои плагины, Вам нужно:
- хорошо знать JS и его подводные камни;
- знать, что такое шаблон "модуль" и уметь писать свои модули;
- помнить, что jQuery.fn - всего лишь псевдоним для jQuery.prototype; добавляя свою функцию к этому свойству, Вы расширяете прототип функции jQuery, и важно ничего там не сломать;
- следовать соглашению, по которому любой плагин jQuery на выходе должен вернуть исходный или модифицированный массив переданных на вход элементов (шаблон "цепочка", есть ещё антишаблон, следующий из этого, называемый "крушение поезда")

Собственно, вот Вам заготовка модуля:
(function ($){
    "use strict";
    function myFunction(items){
        return $(items).each(function(){
            $(this).text("Hello, jQuery!");
        });
    }

    $.fn.hellojQuery = myFunction;
}(jQuery));
Ответ написан
Serhioromano
@Serhioromano
Web Developer
Комментировать
samoilenkoevgeniy
@samoilenkoevgeniy
Lead Full-Stack Web Developer
Я бы для начала выучил js на уровне создания простых слайдеров, переключалок и таймеров.
Ответ написан
Комментировать
Вот хорошая заготовка для написания плагина.

/*
 *  jQuery Boilerplate - v3.3.4
 *  A jump-start for jQuery plugins development.
 *  http://jqueryboilerplate.com
 *
 *  Made by Zeno Rocha
 *  Under MIT License
 */
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

		// undefined is used here as the undefined global variable in ECMAScript 3 is
		// mutable (ie. it can be changed by someone else). undefined isn't really being
		// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
		// can no longer be modified.

		// window and document are passed through as local variable rather than global
		// as this (slightly) quickens the resolution process and can be more efficiently
		// minified (especially when both are regularly referenced in your plugin).

		// Create the defaults once
		var pluginName = "defaultPluginName",
				defaults = {
				propertyName: "value"
		};

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				// jQuery has an extend method which merges the contents of two or
				// more objects, storing the result in the first object. The first object
				// is generally empty as we don't want to alter the default options for
				// future instances of the plugin
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		// Avoid Plugin.prototype conflicts
		$.extend(Plugin.prototype, {
				init: function () {
						// Place initialization logic here
						// You already have access to the DOM element and
						// the options via the instance, e.g. this.element
						// and this.settings
						// you can add more functions like the one below and
						// call them like so: this.yourOtherFunction(this.element, this.settings).
						console.log("xD");
				},
				yourOtherFunction: function () {
						// some logic
				}
		});

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});

				// chain jQuery functions
				return this;
		};

})( jQuery, window, document );
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 3
SerzN1
@SerzN1
Challenge me!
1. основы shamansir.github.io/JavaScript-Garden
2. мини паттерны shichuan.github.io/javascript-patterns
3. паттерны проектирования addyosmani.com/resources/essentialjsdesignpatterns/book
4. MVC по вкусу

и пожалуй самое важное - это понимать когда какой паттерн используется. например название "фабрика" новичку ни о чем не скажет, даже не знаю где почитать про связь реального программирования и применения того или иного паттерна (со временем нарабатывается само)
Ответ написан
unclechu
@unclechu
Я считаю, что начать стоит с освоения UMD (по ссылке также имеются примеры jQuery-плагинов), т.к. на сегодняшний день сколько-нибудь сложный фронт-енд как правило не обходится без AMD или CommonJS. Хорошим живым примером будет jQuery UI.
Ответ написан
C javascript на Codeacademy. Потом теорию закрепить на Udemy.Потом бы взял bootstrap и сверстал себе home page.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы