Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
JavaScript WorkShop
Search
Davi Ferreira
October 04, 2012
Programming
40
370k
JavaScript WorkShop
Workshop de JavaScript - globo.com.
Davi Ferreira
October 04, 2012
Tweet
Share
More Decks by Davi Ferreira
See All by Davi Ferreira
Scrum
daviferreira
2
270
Workshop HTML5 + CSS3
daviferreira
13
3.1k
Workshop Compass @ globo.com
daviferreira
14
2.8k
Other Decks in Programming
See All in Programming
これだけは知っておきたいクラス設計の基礎知識 version 2
masuda220
PRO
23
5.4k
エンジニア未経験が最短で戦力になるためのTips
gokana
0
250
爆速スッキリ! Rspack 移行の成果と道のり - Muddy Web #11
dora1998
1
270
家族・子育て重視/沖縄在住を維持しながらエンジニアとしてのキャリアをどのように育てていくか?
ug
0
260
生成AIを使ったQAアプリケーションの作成 - ハンズオン補足資料
oracle4engineer
PRO
3
110
Being an ethical software engineer
xgouchet
PRO
0
190
Java 24まとめ / Java 24 summary
kishida
3
400
Firebase Dynamic Linksの代替手段を自作する / Create your own Firebase Dynamic Links alternative
kubode
0
220
remix + cloudflare workers (DO) docker上でいい感じに開発する
yoshidatomoaki
0
120
英語 × の私が、生成AIの力を借りて、OSSに初コントリビュートした話
personabb
0
170
ReactFlow への移行で実現するユーザー体験と開発体験の向上
j9141997
0
170
Coding Experience Cpp vs Csharp - meetup app osaka@9
harukasao
0
670
Featured
See All Featured
Music & Morning Musume
bryan
46
6.4k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
The Power of CSS Pseudo Elements
geoffreycrofte
75
5.7k
Agile that works and the tools we love
rasmusluckow
328
21k
Making the Leap to Tech Lead
cromwellryan
133
9.2k
Code Reviewing Like a Champion
maltzj
522
39k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
7.1k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
32
2.2k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
28
1.6k
Fireside Chat
paigeccino
37
3.4k
Navigating Team Friction
lara
184
15k
Gamification - CAS2011
davidbonilla
81
5.2k
Transcript
JS
ABOUT ME desenvolvedor no entretenimento1 15 anos trabalhando com web
autor no tableless @davitferreira
Qualquer aplicação que pode ser escrita em JavaScript, eventualmente vai
ser escrita em JavaScript. -- Jeff Attwood ‘‘
JAVASCRIPT Brendan Eich, Netscape 1995 orientada a objetos, imperativa e
funcional client & server
ECMA SCRIPT Netscape + Microsoft é a linguagem JavaScript, JScript,
ActionScript 3 são os dialetos
‣ variáveis ‣ funções ‣ objetos ‣ dom ‣ eventos
‣ testes ‣ bibliotecas ‣ recursos
tipagem dinâmica escopo local (var) ou global (window) VARIÁVEIS
exemplos var str = "globo.com"; variavelGlobal = "global"; var indice
= 122; var times = ["Flamengo", "Vasco"]; var time = {nome: "Flamengo", titulos: 6, estado: "RJ"};
tipos var num = 22; var num2 = "22"; num
+ num2; // 2222 num + parseInt(num2, 10); num.toString() num === num2 // false typeof num2 // “string”
variável que ainda não recebeu nenhum valor undefined var nome;
typeof nome; // “undefined” nome === undefined // true
var str = "globo.com", indice = 122, times = ["Flamengo",
"Vasco"], time = {nome: "Flamengo", titulos: 6, estado: "RJ"}; legibilidade + otimização declarando
funções ( ) { }
declarando uma função function log (msg) { console.log(msg); } declaração
simples expressão método var log = function (msg) { console.log(msg); }; var App = { log: function (msg) { console.log(msg); } };
escopo var a = 0, b = 1; function soma
() { var a = 2, b = 3; return a + b; } soma(); // 5
constructor + this function Pessoa(nome) { this.nome = nome; this.getNome
= function() { return this.nome; }; } var pessoa = new Pessoa("Davi");
this function Pessoa(nome) { this.nome = nome; $(‘.btn’).click(function () {
alert(this.nome); }); }
this function Pessoa(nome) { var that = this; this.nome =
nome; $(‘.btn’).click(function () { alert(that.nome); }); }
funções auto-executáveis (function (window, $, undefined) { $(window).load(function () {
glb.init(); }); })(window, jQuery, undefined);
arguments toda função possui um array com seus parâmetros function
soma () { var i, resultado = 0; for (i = 0; i < arguments.length; i += 1) { resultado += arguments[i]; } return resultado; } soma(4, 8, 15, 16, 23, 42);
todo mundo é OBJETO { uma string é um objeto
um número é um objeto uma função é um objeto um array é um objeto um boolean é um objeto
exemplos var str = new String ("globo.net"); str.replace(".net", ".com"); var
num = new Number (1); num.toString(); var opaChefe = new Function ("alert(‘Opa’)"); opaChefe(); opaChefe.prototype; // Object
var objeto = { descricao: "uma coleção de propriedades com
chave e valor", "Tipos de valor": "qualquer coisa, exceto undefined" }; estrutura de um objeto
var objeto = { nome: "globo.com", url: "www.globo.com", keywords: ["TV",
"Python"] }; estrutura de um objeto
var objeto = { nome: "globo.com", funcao: function () {
alert(this.nome); } }; estrutura de um objeto
var objeto = { nome: "globo.com", filho: { init: function
() { console.log("started"); } } }; estrutura de um objeto não confundir com herança!
namespace var TVG = { classe: "glb-tvg", init: function ()
{ this.initWidgets(); this.bindKeyboardNavigation(); } }; TVG.init();
herança via prototype
herança via prototype function Pessoa (nome) { this.nome = nome;
} Pessoa.prototype.__unicode__ = function () { return "Pessoa: " + this.nome; }; Pessoa.prototype.idade = 20; var p = new Pessoa("Davi"); p.__unicode__(); p.idade = 32;
herança via prototype Atualizando o prototype de objetos nativos String.prototype.trim
= function() { return this.replace(/^\s+|\s+$/g, ‘’); };
retrospectiva ‣ variáveis possuem escopo global ou local ‣ funções
podem ser construtores ‣ this é uma referência ao escopo ‣ todo mundo é um objeto ‣ javascript não possui classes ‣ todo objeto possui um prototype
[ coleções ]
capitulos = [{ 'titulo': 'Capítulo 1', 'data_exibicao': '2012-09-22', 'conteudos': [
{ 'id': 1, 'titulo': 'Conteúdo 1' }, { 'id': 2, 'titulo': 'Conteúdo 2' }] }]; COLEÇÕES
COLEÇÕES for (i in capitulos) { console.log(capitulos[i]); console.log(capitulos[i].descricao); for (j
in capitulos[i].conteudos) { console.log(capitulos[i].conteudos[j]); } } iteração
(closures)
closures Closure é um tipo especial de objeto que combina
duas coisas: uma função e o escopo no qual esta função foi criada.
var Counter = (function() { var privateCounter = 0; function
changeBy(val) { privateCounter += val; } return { increment: function () { changeBy(1); }, decrement: function () { changeBy(-1); }, value: function () { return privateCounter; } } })(); closures
function makeSizer(size) { return function () { document.body.style.fontSize = size
+'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); size12(); size14(); closures
<DOM> Document Object Model
document window DOM
document.documentElement document.childNodes document.body document.querySelector('#body'); document.getElementById('main'); document.getElementsByClassName('body-main'); DOM <html>
var e = document.createElement('h1'), texto = document.createTextNode('TVG'); e.appendChild(texto); var texto
= document.createTextNode('TVG'), div = document.getElementById('header'); div.insertBefore(texto, div.childNodes[1]); DOM
(e)ventos
BIND var botao = document.getElementById('link-home'), redirect = function () {
window.location.href = 'index.html'; }; botao.addEventListener('click', redirect); botao.onclick = function(){ window.location.href = 'index.html'; }; <button onclick="window.location.href='index.html'"> IE8< attachEvent
UNBIND botao.removeEventListener('click', redirect); botao.onclick = ‘’;
var evtPlantao = new CustomEvent('plantaoCarregado'); document.addEventListener('plantaoCarregado', function(e){...}, false); plantao.dispatchEvent(evtPlantao); PERSONALIZANDO
var evtPlantao = document.createEvent('HTMLEvents'); evtPlantao.initEvent('plantaoCarregado', true, true); document.addEventListener('plantaoCarregado', function (e){ (...) }, false); window.load(function () { plantao.dispatchEvent(evtPlantao); }); Browsers modernos (todos, exceto IE :))
RESPONSABILIDADES $.ajax({ url: '/wherever', success: function(data, status, xhr) { $('selector').append($(data).hide().fadeIn(function(){
$('other-selector').remove(); })); $('yet-another-selector').text('Request successful'); } }); http://floatleft.com/notebook/backbone-has-made-me-a-better-programmer
RESPONSABILIDADES function DataModel() { this.url = '/wherever'; } DataModel.prototype.getData =
function() { $.ajax({ url: this.url, context: this, success: this.onSuccess }); }; DataModel.prototype.onSuccess = function(data) { $(window).trigger('DataModel:success', data); };
DEBUG & VALIDAÇÃO
console if (!this.console) { window.console = { log: function() {
// sua função de log } }; }
console
validação ‣ JSLint ‣ JSHint ‣ Google Closure Linter
TESTES
Jasmine describe("Load Data", function () { it("should call getJSON", function
() { spyOn($, 'getJSON'); TVG.hojeNasNovelas.loadData(); expect($.getJSON).toHaveBeenCalled(); }); it("should set current page to 1", function () { expect(TVG.hojeNasNovelas.currentPage).toEqual(1); }); it("should call showData", function () { spyOn(TVG.hojeNasNovelas, 'showData'); TVG.hojeNasNovelas.loadData(); expect(TVG.hojeNasNovelas.showData).toHaveBeenCalled(); }); });
QUnit test("animate(Hash, Object, Function)", function() { expect(1); stop(); var hash
= {opacity: "show"}; var hashCopy = jQuery.extend({}, hash); jQuery("#foo").animate(hash, 0, function() { equal( hash.opacity, hashCopy.opacity, "Check if animate changed the hash parameter" ); start(); }); });
BIBLIOTECAS & FRAMEWORKS
!== javascript
+ bibliotecas ‣ mootools ‣ ExtJS ‣ YUI ‣ RaphaelJS
‣ Dojo ‣ UnderscoreJS ‣ Prototype ‣ Scriptaculous ‣ CoffeeScript
frameworks ‣ Backbone ‣ AngularJS ‣ KnockoutJS
RECURSOS
None
None
https://github.com/jquery/jquery https://github.com/documentcloud/underscore https://github.com/mootools/mootools-core https://github.com/documentcloud/backbone
developer.mozilla.org/docs/JavaScript
davi.ferreira@corp.globo.com