JS
jQuery Part 2
Agenda
- Events
- Ajax
- Performance
- Templates
jQuery AJAX
jQuery.ajax
Это самый основной метод, а все последующие методы лишь обертки для метода jQuery.ajax.
$.ajax({
url: '/data.json', // указываем URL и
dataType : "json", // тип загружаемых данных
success: function (data, textStatus) { // вешаем свой обработчик
}
});
var jqxhr = $.ajax( "data.json" )
.done(function(data,) {
alert( "success", data );
})
.fail(function(err) {
alert( "error", err );
})
.always(function() {
alert( "complete" );
});
jQuery AJAX
jQuery.ajax
- async — асинхронность запроса, по умолчанию true
- cache — вкл/выкл кэширование данных браузером, по умолчанию true
- contentType — по умолчанию «application/x-www-form-urlencoded»
- data — передаваемые данные — строка иль объект
- dataFilter — фильтр для входных данных
- dataType — тип данных возвращаемых в callback функцию (xml, html, script, json, text, _default)
- type — GET либо POST
- url — url запрашиваемой страницы
jQuery AJAX
jQuery.ajax set header
$.ajax({
url: 'url',
headers: {
'Content-Type': 'application/json'
}
})
jQuery.ajax send post
$.ajax({
type: "POST",
beforeSend: function(requestObj) { // в requestObj хранится информация о реквесте
console.log('we can log some data', requestObj);
requestObj.setRequestHeader("Authority", authorizationToken);
},
url: "api/posts",
data: {
'foo': 'bar'
},
success: function(data) {},
error: function(err) {}
});
jQuery AJAX
jQuery.get
var jqxhr = $.get( "http://www.google.com", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
jQuery.post
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
jQuery AJAX
jQuery.getJSON
var jqxhr = $.getJSON( "data.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
jQuery Events
Using module
(function ($) {
$(document).ready(function () {
var $dateInfo = $('.info__date');
var $btnGetDate = $('.btn__date');
function displayDate (e) {
console.log(this);
$dateInfo.text(new Date().toDateString());
}
$btnGetDate.click(displayDate);
});
}(window.jQuery));
jQuery Events
Events: resize and click
$(function() {
var $infoSizePage = $('.info__size-page');
$(window).resize(function (e) {
$infoSizePage.text(
'Width: ' + window.innerWidth + ' Height: ' + window.innerHeight
);
});
$('.button').click(function(e) {
$(this).text('Change text');
// $(e.target).text('change text')
});
});
List of Events
change — event is sent to an element when its value changes.
click — mousedown → mouseup → click
dblclick — event is sent to an element when the element is double-clicked
resize — event is sent to the window element when the size of the browser window changes
select — event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.
keypress — keydown → keypress → keyup
and many other....
focus, blur, focusin, focusout, keydown, keyup, load, unload, mousedown, mouseup, mousemove, mouseenter, mouseleave, mouseover, mouseout
Mobile Events
orientationchange, touchstart, touchmove, touchend, touchcancel, and other
Event Handler Attachment
.bind() → Attach a handler to an event for the elements (less the jQuery 1.7).
.unbind() → Remove a previously-attached event handler from the elements.
.delegate() → Deprecated.
.undelegate() → Remove a handler from the event for all elements which match the current selector
.live() → Deprecated.
.die() → Remove event handlers previously attached using .live() from the elements.
.on() → Attach an event handler function for one or more events to the selected elements.
.off() → Remove an event handler.
.one() → The handler is executed at most once per element per event type.
.trigger() → Execute all handlers and behaviors attached to the matched elements for the given event type.
.triggerHandler() → Execute all handlers attached to an element for an event.
Event Handler on and one
$('.btn__on').on( 'click', function() {
console.log( "This will be displayed." );
});
$('.btn__one').one( 'click', function() {
console.log( "This will be displayed only once." );
});
$('.btn__on-with-off').on( 'click', function(event) {
console.log( "This will be displayed only once." );
$( this ).off( event );
});
Events trigger()
(function ($) {
$(document).ready(function () {
var $btnGetDate = $('.btn__get-date');
function displayDate () {
var result = $('.result');
result.text(new Date().toDateString());
}
$btnGetDate.click(displayDate);
$btnGetDate.click();
//or
$btnGetDate.trigger('click');
});
}(window.jQuery));
Events triggerHandler()
$(document).ready(function () {
var $myForm = $('#MyForm');
$myForm.on('submit', function () {
console.log('Form Submit');
});
$('.trigger-button').on('click', function () {
$myForm.triggerHandler('submit');
});
});
- Метод .triggerHandler() не вызывает стандартных событий (к примеру отправку формы).
- Если мы вызовем событие focus из методом .triggerHandler(), то стандартное поведение браузера не сработает, а запустятся только обработчики.
Events on() and off()
$(document).ready(function () {
function flash () {
$('div').show().fadeOut('slow');
}
$('#bind').on('click', function () {
$('body')
.on('click', '#theone', flash)
.find('#theone')
.text('Can Click!');
});
$('#unbind').on('click', function () {
$('body')
.off('click', '#theone', flash)
.find('#theone')
.text('Does nothing...');
});
});
Events on()
function flash (event) {
$('.flash')
.text(event.target.className + ' ' + event.target.nodeName)
.show()
.fadeOut('slow');
}
function addButton () {
if ($('.test').length) {
return;
}
$('body').append('<button class=\'test\'>Click Meeee</button>');
}
// SET HANDLER
$('body').on('click', '.test', flash);
// READY
$(document).ready(function () {
$('.btn__click-me').click(addButton);
});
Performance
$.each( myArray, function( index, item ) {
var newListItem = "<li>" + item + "</li>";
$( "#ballers" ).append( newListItem );
});
var myHtml = "";
$.each( myArray, function( i, item ) {
myHtml += "<li>" + item + "</li>";
});
$( "#ballers" ).html( myHtml );
Bad example
Good example
Append Outside of Loop
Performance
$( "#nosuchthing" ).slideUp();
var elem = $( "#nosuchthing" );
if ( elem.length ) {
elem.slideUp();
}
Bad example
Good example
check if exists
Performance
$( ".data table.attendees td.gonzalez" );
// Better: Drop the middle if possible.
$( ".data td.gonzalez" );
// Unoptimized:
$( "div.data .gonzalez" );
// Optimized:
$( ".data td.gonzalez" );
Optimize Selectors
Link Avoid Excessive Specificity
Specificity
// Fast:
$( "#container div.robotarm" );
// Super-fast:
$( "#container" ).find( "div.robotarm" );
// Extremely expensive.
$( ".buttons > *" );
// Much better.
$( ".buttons" ).children();
ID-Based Selectors
Avoid the Universal Selector
Good Practice
var myDiv$ = $('#myDivId');
myDiv$.hide();
myDiv$.show();
//cool
$('div.close, button.close, input.close')
.click(doSomething);
//not cool
$('div.close').click(doSomething);
$('button.close').click(doSomething);
$('input.close').click(doSomething);
Always Cache jQuery Objects before use
Try to make code simpler using group queries
//cool
$("#myID")
.css({ "color": "blue", "font": "Arial"})
.text("Hello!");
//not cool
$("#myID").css("color", "blue");
$("#myID").css("font", "Arial");
$("#myID").text("Hello!");
Use Chaining
Links
Examples
JS
By Oleg Rovenskyi
JS
jQuery
- 539