Upload
alexandre-marreiros
View
570
Download
0
Embed Size (px)
DESCRIPTION
A formation i give at innovagency at 2 years ago when Jquery was a child. But it seems it wstill a great conceptual introdution to the technology.
Citation preview
JQUERY A TECHNICAL OVERVIEW
Abril-2009, Alexandre Marreiros
Introduction
Agenda No agenda
Sinta-se a vontade para interromper
Pergunte
Comente
Todas as perguntas são validas.
Javascript Libraries/Framework
Porquê do uso? Visão da página html como um conjunto
sendo um conjunto de objectos; em deterimento de navegação pelo DOM.
CrossBrowsing styling, este tipo de plataformas procura dar suporte a aplicação de estilos de igual modo em qualquer browser;
Focus na interacçaõ com o utilizador; Facilitam a execução de pedidos
assincronos.
DOM (Document Object Model) É uma interpretação cross plataform e
relacional de um documento. Permite-nos olhar um qualquer documento que o suporte como um conjunto de elementos relacionados entre sí e com as suas próprias especificidades.
A kind off a Object Ao utilizar o Dom como forma de
interpretação de um documento, deixamos de ver o html como um conjunto de tags para ter uma visão de um conjunto de elementos.
Cada elemento tem a sua forma de relacionamento com os restantes assim como os seus próprios atributos.
Cada elemento é assim interpretado como um objecto…
A object vision off the Document
Permite isolar cada um dos elementos; Entende cada elemento como um conjunto
de atributos propriedades e relações com outros elementos;
Permite uma abstração do todo e aconcentração apenas no atomo;
Etc…
JQuery “Is a new kind of JavaScript Library.
jQuery is a fast and concise JavaScript
Library that simplifies HTML document
traversing, event handling, animating, and
Ajax interactions for rapid web development.
jQuery is designed to change the way that
you write JavaScript.
Lightweight Footprint ,CSS3 Compliant,
Cross-browser” – Jquery.com
Jquery IIPreparado com um conjunto de animações,
efeitos e widgets.
Basics: show(), hide(), toggle() Slide: slideUp (), slideDown() Fading: fadeIn(), fadeOut() Custom
A maior parte das animações permite
estabelecer a velocidade e até callbacks
Jquery Foundation Anonymous methods
Factory Method
Selectors
JQuery Foundation II Anonymous methods
Métodos anonimos são métodos sem nome que são declarados em runtime
Permitem maior legibilidadedo codigoNao sobrecarregam o engine do browser
pois o código de um método anonimo só é interpretado no acto de execução
Em JQuery: $( function(){ alert( "I'm anonymous!" ); } );
jQuery Foundation IIIFactory Method$() nomenculatura jQuery() factory method $( function ) – executa a função após todos os
objectos DOM terem sido carregados$( selector ) – retorna uma coleção de
elementos que tenham como atributo o selector$( html ) – retorna todos os elementos html que
foram criados após o carregamento da página. Uma coleção de elementos é designada é
um stack.
jQuery Foundation IV Selectors
Css slectors
Xpath Selectors
Custom Selectors
jQuery Foundation V Css Selectors $(“Selectors”)
Suporta todos os selectores definidos nas especificações de css
da w3c e permite através deles obter elementos e manipula-los…
Quer pelos nomes das classes, quer pela localização, quer pelo
seu contexto relacional. $( "#header" ) – retorna uma coleção com todos os elementos que tenham o
id header; $( "div.note" ) – retorna todos os divs que contenham a class note associada; $( "p" ) – retorna uma coleção com todos os elementos p contidos no
documento; $( "ul.list li" ) – combinação das duas anteriores; $( "a[ rel = 'home' ]" ) – coleção de links cujo atributo rel é "home“ $( “#selected-plays > li" ) – retorna uma coleção de todos os elementos cujo
id é selected-plays e que tem um filho do tipo li. Etc..
Helper functions getParentWithClass() getParentWithTagName() Etc…
jQuery Foundation VI Xpath selector
Xml Path language, permite iterar por diferentes elementos de um documento XML, e interpretar cada um deles como um objecto.○ $( ‘a[@title]’ ) – retorna o valor do atributo title de
todos os elementos a;○ $( ‘div[ul]’ ) – retorna uma coleção com todos os
elementos div do documento que tem um elemento ul;○ A selecção utilizando atributos permite utilizar uma
sintaxe proxima das regular expressions permitndo insturções do tipo:$(‘a[@href^=“mail to”]’) – retorna todos os elementos do tipo a
que contenham um href começado por mail to;$(‘a[@href$=“pdf”]’) – retorna todos os elementos do tipo a
que contenham um href terminado por pdf
jQuery Foundation VII Custom Selectors
A todos os selectores definidos o jQuery acrescentam ainda o seu conjunto de selectores. Particularmente uteis para a manipulação de tabelas e outros elementos complexos.
Em elementos contentores o são disponibilizadas intruções do tipo:○ $(‘tr.odd’) – obtem todos os tr impares○ $(‘tr.even’) – obtem todos os tr pares○ $(‘div:nth-child(1)’) – obrtem todos os divs que são
o primeiro filho do contentor onde se encontram.
Rules off $()$() returns a jQuery collection containing 0+ elements Calls on an empty collection don't error When accessing values, usually only the first
element is used When mutating values, usually all elements in
collection are updated When mutating values, the jQuery object is usually
returned - this allows for method chaining $().addClass( "one" ).addClass( "two" ).removeClass(
"one" ) NOTE: Method chaining is "cool", but can hurt
readability - don't overuse
Methods over jQuery Object $().attr( name ) - Gets value of given attribute for first element $().attr( name, value | {options} ) - Sets values for all elements $().addClass() - Adds CSS class to all elements $().removeClass() - Removes CSS class from all elements $().css( name ) - Gets CSS value of given property for first element $().css( name, value | {options} ) - Sets CSS properties for all elements $().html() - Gets the inner HTML of the first element $().html( html ) - Sets the inner HTML of all elements $().text() - Gets the combined text of all elements $().text( text ) - Sets the text value of all elements $().val() - Gets the value attribute of first element $().val( val ) - Sets the value attribute of all elements $().append( html | element | jQuery ) - adds given content to the selected content $().appendTo( selector ) - adds given set to the selected set $().prepend() / $().prependTo() - Same as above, but prepends $().before( content ) - Inserts the given content before the selected elements $().after( content ) - Inserts the given content after the selected elements $().remove() - Removes selected elements from DOM $().empty() - Removes all children from given set of elements $().clone() - Creates a copy of the given set $().filter( selectors | function ) - Returns a sub-set of collection matching filter $().not( selectors ) - Returns a sub-set of collection not matching filter
Nota: A filtragem de elementos não é destrutiva da coleção
Methods over jQuery Object in Dom
$().find( selectors ) - Gets the elements in the context of the given collection
$().children( [selectors] ) - Gets the set of children of given elements
$().parent( [selectors] ) - Gets the parent of each element in the given set
$().prev( [selectors] ) - Gets the previous element of each element in given set
$().prevAll( [selectors] ) - Gets all the previous elements of each element in given set
$().next( [selectors] ) - Gets the next element of each element in given set
$().nextAll( [selectors] ) - Gets the all the next elements of each element in given set
Iterating over jQuery objectQuando o stack é mesmo uma coleção$().each( function( intIndex, objElement ) ) –
identico ao foreach de muitas linguagensÉ uma função de contexto a iteração é feita
sobre o elemento DOM indexado;
Events You can bind as many handlers to a given event $().bind( eventType, function( objEvent ){} ) - Bind given
function to given event type on given collection Many built-in short hands: $().bind( "click", fn ) == $
().click( fn ) $().trigger( eventType ) - Manually trigger event handlers Many built-in short hands: $().trigger( "click" ) == $().click() return( false ) - In event handler, prevents default behavior
and event bubbling objEvent.preventDefault() - In event handler, prevents
default event (allows bubbling) objEvent.stopPropagation() - In event handler, prevents
bubbling (allows default behavior) NEW: live() / die() - Automatically wires events based on
selectors
Extending jQuery Extender a biblioteca jQuery está
pensado a dois niveis através de plugins ou de novos selectorsExtender funções (extend $ object) Extenmder funções dos contentores(
extend $.fn object) Extender os selectors (extend $.expr[':'] object)
Referencias www.jquery.com – site oficial; http://plugins.jquery.com – conjunto de
plugins e exemplos Learning Jquery, better design and web
development with simple Javascript techniques, Jonathan Chaffer & Karl Swedberg – Conceitos base da biblioteca;
JQuery Reference Guide Jonathan Chaffer & Karl Swedberg – nutshel e referencia de cabeceira;
JQuery in action – exemplos práticos e aplicação.