scti 2011 minicurso jquery

Download Scti 2011 minicurso jquery

If you can't read please download the document

Upload: ciberglo

Post on 16-Apr-2017

1.302 views

Category:

Technology


0 download

TRANSCRIPT

Javascript + jQuery:With great power, comes great responsibility

http://www.slideshare.net/ciberglo/scti-2011-minicurso-jquery

Gabriel Lima
@glima5
github.com/gabriellima

Balanceando: Bsicos

typeof("") == "string"

typeof(0) == "number""2" + "2" = "22"

typeof(true) == "boolean"

if ( 4 && !0 && "test" && !"" && !undefined && { } ){

alert("true");

}

Balanceando: Funes

Balanceando: Objetos

Tudo que no uma string, um nmero ou booleano

var shape = new Shape();

var obj = { }; // Object literal, == "new Object()"

var arr = [ ]; // Array literal, == "new Array()"

var exp = /[0-9a-z]/ig; // reg exp literal

Balanceando: Hashes

Objetos podem ser manipulados como hashes:

var lastNames = { };

lastNames["Jason"] = "Horton";

lastNames["Matheu"] = "Chambers";

lastNames["Rohit"] = "Mistry";

for ( var key in lastNames ) {

alert( key + " " + lastNames[key] );

}

Exemplo: Array sorting

var arr = ["a","f","Z","b","x", "o", "A"].sort();

// retorna ["A", "Z", "a", "b", "f", "o", "x"] ... rpido mas no to legal...

Exemplo: Array sorting

var arr = ["a","f","Z","b","x", "o", "A"].sort( by_alpha )

// retorna ["a", "A", "b", "f", "o", "x", "Z"] ... mais til

Scope

var iAmGlobal = 5 * 5;

function doSomething() { var inner = 5 * 5;};

var g = "global";function go() { var l = "local";}go();console.log(l); // throws a reference error

Scope: How it works

function go() { console.debug(this); }go();

var myObject = { go: function() { console.debug(this); }};myObject.go(); // console.debugs a reference to myObject

Scope: How it works

function MyClass() { this.go = function() { console.debug(this); }};var instance1 = new MyClass();var instance2 = new MyClass();

instance1.go(); // console.debugs a reference to the MyClass instance1instance2.go(); // console.debugs a reference to the MyClass instance2

Qual o lugar do javascript?

JavaScript bom para clculo, converso, acesso a fontes externas (Ajax) e definio de comportamentos na interface (eventos).

Todo o resto deve ser deixado pra tecnologia que temos pra fazer o servio.

Progressive enhancement

Web Page :: Printed pageWeb Site Web Browser ?No!

Web Browser Web PageTeleviso Show de msica

Sim!

Progressive enhancement 2.0

Progressive enhancement 2.0

Chrome

Progressive enhancement 2.0

Firefox

Progressive enhancement 2.0

IE 9

Progressive enhancement 2.0

IE 6

Progressive enhancement 2.0

Netscape 4

Melhor experincia de acordo com capacidade do dispositivo

Bordas curvas, Sombra, Gradient CSS

Script avanado e comportamentos somente com APIs javascript nativas

Navegadores antigos quase sempre precisam de muito mais cdigo pra fazer a mesma coisa!

Mas as pessoas no vo notar?

O que voc viu?

Voc no est sozinho

Keep javascript out of HTML

wrong!

better!

(function(){
var search_button = document.getElementById('do_search');
search_button.onclick = function(event) {
do_something();
}
})();

HTML vs Javascript

Fuja de inserir HTML diretamente no cdigo javascript

Se voc percebe que est digitando muito cdigo HTML num codigo javascript, voc deve estar fazendo algo errado

Keep HTML out of Javascript

var element = document.getElementById('container');element.innerHTML =

Keep Javascript out of CSS

.foo {
width: expression(document.offsetwidth + px);
}

Keep CSS out of Javascript

Estilos no devem ser confundidos com comportamentos

Exemplo: borda vermelhaColoque uma borda vermelha em todos campos com uma classe required quando estiverem vazios.

Exemplo: borda vermelha

Exemplo: borda vermelha

Event handlers should only handle events

//the wrong way!!!function handleClick(event){ var popup = document.getElementById("popup"); popup.style.left = event.clientX + "px"; popup.style.top = event.clientY + "px"; popup.className = "reveal";}

Don't pass the event object around

//better, but still wrongfunction handleClick(event){ showPopup(event);}function showPopup(event){ var popup = document.getElementById("popup"); popup.style.left = event.clientX + "px"; popup.style.top = event.clientY + "px"; popup.className = "reveal";}

Separe corretamente os event handlings

//fuck yeah!!function handleClick(event){ showPopup(event.clientX, event.clientY);}function showPopup(x, y){ var popup = document.getElementById("popup"); popup.style.left = x + "px"; popup.style.top = y + "px"; popup.className = "reveal";}

Avoid global functions and variables

function handleClick(event){ showPopup(event.clientX, event.clientY);}function showPopup(x, y){ var popup = document.getElementById("popup"); popup.style.left = x + "px"; popup.style.top = y + "px"; popup.className = "reveal";}

Create a single global (se necessrio)

var Controller = { handleClick: function(event){ this.showPopup(event.clientX, event.clientY); }, showPopup: function (x, y){ var popup = document.getElementById("popup"); popup.style.left = x + "px"; popup.style.top = y + "px"; popup.className = "reveal"; }};

Separe configuraes

function validate(value) { if (!value) { alert("Invalid value"); location.href = "/errors/invalid.php"; }};

Separe configuraes

var config = { urls: { invalid: "/errors/invalid.php" }, strs: { invalidmsg: "Invalid value" }};function validate(value) { if (!value) { alert(config.strs.invalidmsg); location.href = config.urls.invalid; }};

Separe configuraes

Todas URLs requeridas pelo javascript

Qualquer texto exibido para o usurio

Qualquer HTML que precisa ser criado pelo javascript

Configuraes (exemplo: itens por pgina)

Valores nicos repetidos

Qualquer coisa que talvez seja modificada no futuro, e utilizada em mais de um lugar

Otimizando

Loops:var names = ['George','Ringo','Paul','John'];for(var i=0;i 0 && (+new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25);}

Web Workers to the rescue!

Web Workers

Asynchronous JavaScript execution

Execution happens in a separate process

Not on the UI thread = no UI delays

Data-driven API

Data is serialized when sending data into or out of Worker

No access to DOM, BOM

Completely separate execution environment

//in page
var worker = new Worker("code.js");

worker.onmessage = function(event){ alert(event.data);};worker.postMessage("Nicholas");

//in code.js

self.onmessage = function(event){ self.postMessage("Hello, " + event.data + "!");};

Resumo de Responsive UI

UI thread is used both for JavaScript execution and UI updates

UI cannot be updated while JavaScript is executing

Keep JavaScript execution to 50ms use timers and/or web workers to offload processing

Jquery: Traversing

jQuery

Um Faz quase tudo da vida

Porm, deve ser usado com cautela, pois ao mesmo tempo que pode melhorar o cdigo pode s vezes prejudicar a performance

Principal teoria: html / css selectors

http://code.jquery.com/jquery-latest.js// jQuery 1.7

Jquery: Traversing

O HTMLdiv.container o 'wrapping element'

div.photo, div.title and div.rating so filhos 'imediatos' do div.container

Cada div.star filho de div.rating

Quando uma div.star tem a class 'on', uma estrela selecionada

Mas por qu traversing?

O select do jQuery j no poderoso o suficiente?

Jquery: Traversing

Bem, no exemplo anterior, queremos que quando o usurio clicar numa dada estrela, todas as estrelas esquerda sejam tambm selecionadas, e todas as direita no sejam selecionadas

$('.star').click(function(){ $(this).addClass('on'); // How to select the parent div of 'this'? // How to select stars to the left side of 'this'? });

.children

This function gets the immediate children of a set of elements.

This can be very handy in a variety of situations. Look at the figure below:The container of the stars are selected initially.

A selector expression is passed to children() to narrow the result down to only the full stars.

If children() receives no parameters, all immediate children will be returned.

No grandchildren will be returned. Sorry.

.children

.filter

This function filters out elements from the wrapped set using a passed selector expression. Any elements that doesnt match the expression will be removed from the selection.

The following example should be pretty straightforward. The full stars are filtered out from a collection of all five stars.

.not

Quite the opposite from filter(), not() removes the matching elements from the wrapped set.

See the example below. Even stars are removed from the selection, leaving only the odd ones.

Notice! Even and odd selectors are zero-indexed. They count index from 0, NOT 1.

.add

What if we want to add some elements to the wrapped set? The add() function does this.

Again, very straightforward. The photo box is added to the selection.

.slice

Sometimes we may wish to obtain a subset of the wrapped set, based on the position of elements within the set. And slice() is the way to go.The first parameter is the zero-based position of the first element to be included in the returned slice.

The second parameter is the zero-based index of the first element NOT to be included in the returned slice. If omitted, the slice extends to the end of the set.

So slice(0, 2) selects the first two stars.

.slice

.parent

The parent() function selects the direct parent of a set of elements.

As shown in the figure below, the first stars direct parent is selected. Very handy, hah?

It should be noted that only the direct parent will be returned, which is why its singular. No grandparent or ancestors will be selected.

.parents

This one is plural! The parents() function selects all ancestors of a set of elements. I mean ALL ancestors from the direct parent all the way up to body and html. So its best to pass a selector expression to narrow down the result.

By passing .container to parents(), div.container, which actually is the grandparent of the first star, is selected.

.siblings

This function selects all siblings (brothers and sisters) of a set of elements. An expression can be passed to filter the result.

Look at the example:Whos the first stars siblings? The other four stars, right?

The odd siblings are selected as shown. Again, the index is zero-based. Look at the red numbers below the stars.

.prev e .prevAll

The prev() function selects the previous (one) sibling

The prevAll() selects all previous siblings of a set of elements.

This is super handy if youre building a star rating widget. The previous siblings of the third star are selected.

.next e .nextAll

These functions work in the same way as prev and prevAll, except for that they select the NEXT siblings.

Traversing - Soluo

Vejamos como essa funo resolve nossa dor de cabea:

$('.star').click(function(){ $(this).addClass('on'); // How to select the parent div of 'this'? $(this).parent().addClass('rated'); // How to select stars to the left side of 'this'? $(this).prevAll().addClass('on'); $(this).nextAll().removeClass('on'); });

Traversing

This is the very problem we mentioned early in this tutorial, right? Several traversing functions are used in these lines of code.In Line 5, look at the use of parent(). Easy, hah?

In Line 8 and 9, prevAll() and nextAll() select the to-be full stars and empty stars.

Traversing can be even more powerful when used together.

The output of one function can be the input of another that is to say, theyre chainable.

Multi-select transfer

$().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').appendTo('#select2'); });

$('#remove').click(function() { return !$('#select2 option:selected').appendTo('#select1'); }); });

Multi-transfer

$().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').remove().appendTo('#select1'); }); }); a { display: block; border: 1px solid #aaa; text-decoration: none; background-color: #fafafa; color: #123456; margin: 2px; clear:both; } div { float:left; text-align: center; margin: 10px; } select { width: 100px; height: 80px; } Option 1 Option 2 Option 3 Option 4 add >>