More Related Content Similar to I tmozg js_school_jquery Similar to I tmozg js_school_jquery (20) I tmozg js_school_jquery2. 2
jQuery плагины
• Экономят время
• Упрощают код скриптов
• Позволяют другим использовать ваш код
3. 3
Инициализация
jQuery.fn.myPlugin = function() {
// Код крутого плагина
};
4. 4
Правильная инициализация
(function( $ ) {
$.fn.myPlugin = function() {
// Код крутого плагина
};
})( jQuery )
5. 5
Контекст
(function( $ ){
$.fn.myPlugin = function() {
// "this" уже является jQuery объектом
this.fadeIn('normal', function() {
// "this“ является DOM объектом
});
};
})( jQuery );
$('#element').myPlugin();
6. 6
Работающий плагин
(function( $ ){
$.fn.maxHeight = function() {
var max = 0;
this.each(function() {
max = Math.max( max, $(this).height() );
});
return max;
};
})( jQuery );
var tallest = $('div').maxHeight();
7. 7
Поддерживаем chaining
(function( $ ){
$.fn.lockDimensions = function( type ) {
return this.each(function() {
var $this = $(this);
// Работаем с каждым элементом
});
};
})( jQuery );
8. 8
Параметризация
(function( $ ){
$.fn.tooltip = function( options ) {
// Массив значений по умолчанию
var settings = $.extend( {
'location' : 'top',
'background-color‘ : 'blue'
}, options);
return this.each(function() {
// Код плагина
});
};
})( jQuery );
$('div').tooltip({ 'location' : 'left' });
9. 9
Namespacing
(function( $ ){
$.fn.tooltip = function( options ) {
// Это
};
$.fn.tooltipShow = function( ) {
// очень
};
$.fn.tooltipHide = function( ) {
// плохо
};
$.fn.tooltipUpdate = function( content ) {
// !!!
};
})( jQuery );
10. 10
Список методов
var methods = {
init : function( options ) { },
show : function( ) { },
hide : function( ) { },
update : function( content ) { }
};
11. 11
Логика выбора нужного метода
$.fn.tooltip = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this,
Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on
jQuery.tooltip' );
}
};
12. 12
Вызов метода
// Вызываем init метод
$('div').tooltip();
// Вызываем init метод с параметрами
$('div').tooltip({ foo : 'bar' });
// Вызываем hide метод
$('div').tooltip('hide');
// Вызываем update метод с параметром
$('div').tooltip('update', 'This is the new tooltip content!');
13. 13
Итоги
• (function( $ ){ /* код плагина */ })( jQuery );
• Поддерживайте chaining
• Передавайте настройки через {}
• Всегда используйте namespace
• Один namespace – один плагин
14. 14
Вопросы?
Павлючков
Даниил
d.pavluchkov@itmozg.ru