• Nenhum resultado encontrado

JAVASCRIPT DE QUALIDADE HOJE, AMANHÃ E SEMPRE GUILHERME CARREIRO THIAGO OLIVEIRA

N/A
N/A
Protected

Academic year: 2021

Share "JAVASCRIPT DE QUALIDADE HOJE, AMANHÃ E SEMPRE GUILHERME CARREIRO THIAGO OLIVEIRA"

Copied!
55
0
0

Texto

(1)

JAVASCRIPT DE

QUALIDADE

HOJE, AMANHÃ

E SEMPRE

GUILHERME CARREIRO

THIAGO OLIVEIRA

(2)

GUILHERME CARREIRO

Rubyist and code deisgner

THIAGO OLIVEIRA

(3)
(4)
(5)
(6)
(7)
(8)

prototype

a = ["Javascript", "Ruby", "Java", "Python", "Haskell"];

!

a.first();

// => TypeError: Object Javascript,Ruby,... has no method 'first'

!

Array.prototype.first = function() {

return this[0];

}

!

a.first();

(9)

var

function devcamp () { a = 2; novoEvento(a); }; ! devcamp(); ! console.log(a); // => 2

(10)

var

function devcamp () { var a = 2; novoEvento(a); }; ! devcamp(); ! console.log(a); // => a is not defined

(11)

var

var js = 'JS';

function teste() {

var ruby = 'Ruby';

console.log(ruby); console.log(js); var js = 'Javascript'; } ! teste(); // => "Ruby" // => undefined

(12)

var js = 'JS';

function teste() {

var js, ruby = 'Ruby';

console.log(ruby); console.log(js); js = 'Javascript'; } ! teste(); // => "Ruby" // => undefined

var

(13)
(14)

var

function f () { var i = 0; for (; i < 10; i++) { var js = 'JavaScript' } console.log(js); } f(); // => JavaScript

(15)

var

let

function f () { var i = 0; for (; i < 10; i++) { let js = 'JavaScript'; } console.log(js); } f(); // 'js' is not defined function f () { var i = 0; for (; i < 10; i++) { var js = 'JavaScript' } console.log(js); } f(); // => JavaScript

(16)

var

let

function f () { var i = 0; for (; i < 10; i++) { let js = 'JavaScript'; } console.log(js); } f(); // 'js' is not defined

const

! const js = ‘JavaScript'; ! js = ‘Ruby’;

// const 'js' has already been // declared. ! ! function f () { var i = 0; for (; i < 10; i++) { var js = 'JavaScript' } console.log(js); } f(); // => JavaScript

(17)
(18)
(19)

Código Javascript misturado com código HTML

<!DOCTYPE html>

<html>

<head></head>

<body>

<input type="button" onclick="validateAndSubmit();" />

<script type="text/javascript"> doSomething();

</script>

</body>

(20)

Código Javascript misturado com código HTML

<!-- index.html --> <!DOCTYPE html> <html> <head> </head> <body>

<input type=“button" id=“btn” />

<script src=“devcamp.js" type="text/javascript"></script>

</body>

</html>

!

// devcamp.js

var btn = document.getElementById('btn');

btn.addEventListener('click', validateAndSubmit);

!

(function(){

doSomething(); }());

(21)

CSS misturado com código Javascript

var botao = document.getElementById('botao'); !

botao.onclick = function(e) {

this.style.border = '2px solid red'; }

(22)

CSS misturado com código Javascript

var botao = document.getElementById('botao'); !

botao.onclick = function(e) {

this.className = 'special-button'; }

(23)

Lógica de negócio no Javascript

var botao = document.getElementById('botao'), saldo = <%= @saldo %>; ! botao.onclick = function(e) { if(saldo > 0) { comprar(); } else { return false; } }

(24)

Código HTML no Javascript

var botao = document.getElementById('botao'), saldo = <%= @saldo %>;

!

botao.onclick = function(e) {

var status = document.getElementById('status'),

html = '<div>',

foto = getUserPicture();

if(saldo > 0) {

html += '<img src="' + foto + '" alt="Foto" />'; html += '<h1>Saldo: ' + saldo + ' =)</h1>';

}

html += '</div>';

status.innerHTML = html;

(25)

!

<!-- index.html -->

<script src="jquery.tmpl.js" type="text/javascript"></script> <!-- ... -->

<div id="template"> <div>

<img src="${path}" alt="Foto" /> <h1>Saldo: ${saldo} =)</h1>

</div> </div> !

// devcamp.js

var botao = $('#botao'),

template = $('#template'), saldo = <%= @saldo %>;

botao.click(function(e) {

var html, status = $(‘#status'), foto = getUserPicture(); if (saldo > 0) {

html = $.tmpl(template.html(), {saldo: saldo, path: foto}).html(); }

status.html(html); });

(26)

HTML

CSS

JS (client side)

Ruby (server side)

Conteúdo

Estilo

Lógica de

apresentação

Lógica de

negócio

Fonte: http://www.slideshare.net/fgalassi/refactoring-to-unobtrusive-javascript

Separar responsabilidades

(27)
(28)
(29)

function object(o) { function F() {} F.prototype = o; return new F(); } ! var parent = { name: 'Papa' } !

var child = object(parent);

!

console.log(child.name); // => Papa

(30)
(31)

! function Parent() { this.name = 'Joey'; } ! Parent.prototype.say = function() { console.log('I\'m ' + this.name); } ! function Child() {

this.name = 'Dee Dee';

}

!

function inherits(Child, Parent) {

Child.prototype = Object.create(Parent.prototype);

}

!

inherits(Child, Parent);

!

var a = new Child();

!

a.say(); // => I'm Dee Dee

(32)

var SuperHuman = Person.extend(function (name) { // ... }).methods({ walk: function() { this.supr(); this.fly(); }, fly: function() { // ... } }); ! new SuperHuman(‘Zelda').walk();

Padrão klass

https://github.com/ded/klass

(33)
(34)
(35)

class Man {

constructor (name) {

this.name = name;

}

say (message) {

return this.name + ': ' + message;

} }

!

let john = new Man('John Doe’);

!

john.say('Hi!');

// => John Doe: Hi!

(36)

class Man {

constructor (name) {

this.name = name;

}

say (message) {

return this.name + ': ' + message;

} }

!

class SuperMan extends Man { constructor () { super('Clark Kent'); } fly () { return 'Flying...'; } } !

let superMan = new SuperMan(); superMan.say('Yeah!');

// => Clark Kent: Yeah! superMan.fly();

(37)
(38)

Arrow functions

var plus = function (a, b) {

return a + b;

};

!

var plus = (a, b) => {

return a + b;

};

!

var plus = (a, b) => a + b;

!

(39)

Arrow functions

[1, 2, 3].map(function (i) { return i * i; }); // => [1, 4, 9] ! [1, 2, 3].map(x => x * x); // => [1, 4, 9]

(40)

Modules

// plugins/math.js

export function square (a) { return a * a;

}

! !

// index.js

import {square} from 'plugins/math.js'; square(1);

(41)

Modules

// plugins/math.js

export function square (a) { return a * a;

}

! !

// index.js

import 'plugins/math.js' as Math; Math.square(1);

(42)

Default arguments

var g = function (a, b) {

a = a || 1; b = b || 1; return a + b; } ! var f = function (a = 1, b = 1) { return a + b; } ! f(); // => 2 ! f(2, 2); // => 4 ! f(undefined, 7); // => 8

(43)

Rest parameters

var f = function (a = 1, ...b) { console.log(a, b); } ! f(1); // => 1 [] ! f(1, 2); // => 1 [2] ! f(1, 2, 3); // => 1 [2, 3]

(44)

Interpolation

let a = 4; let b = 3;

let code = `${a} + ${b} = ${a + b}`; // => 4 + 3 = 7 ! let code = ` def plus(a, b) a + b end `;

(45)
(46)
(47)
(48)
(49)
(50)
(51)
(52)
(53)
(54)
(55)

PERGUNTAS?

OBRIGADO! :)

Referências

Documentos relacionados

De acordo com os requisitos gerais deste presente projeto, os quais necessitavam de uma aplicação móvel para dispositivos Android, e que esta auxiliasse de maneira

PARÁGRAFO 1º - A relação nominal ( Ficha de Inscrição de Atletas ) será feita por sorteio juntamente com os 02 membros da comissão técnica, durante a

Encorajado como está pela determinação da maioria das lideranças das Igrejas de preservar o MECC como instituição, apesar de todos os existentes desafios que

alimentação e distribuição de energia eléctrica, elaboração dos processos de licenciamento, engenharia de detalhe, desenvolvimento de software, instalação e colocação

O tema é tão relevante que levou a Organização Mundial da Saúde (OMS) a estabelecer 16 de outubro como o Dia Mundial da Alimentação, data que deve servir para encorajar ainda mais

A Arara-azul de nome científico Anodorhynchus hyacinthinus, vive na floresta Amazônica, pesa 1,3 kg, suas principais características são: viver em família, em

É a autopoiese social que equaciona as múltiplas possibilidades de comunicações, de forma que tudo que ocorre se dá através da (auto)produção recíproca de

A partir do presente estudo conclui-se que após a intervenção realizada nas aulas de recreação se obteve uma melhoria do consumo máximo de oxigênio nas