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
260
Workshop HTML5 + CSS3
daviferreira
13
3.1k
Workshop Compass @ globo.com
daviferreira
14
2.8k
Other Decks in Programming
See All in Programming
Crafting Cross-Platform Adventures: Building a Game Engine with Kotlin Multiplatform
dwursteisen
0
130
AndroidアプリのUIバリエーションをあの手この手で確認する / Check UI variations of Android apps by various means
tkmnzm
1
190
状態管理ライブラリZustandの導入から運用まで
k1tikurisu
3
470
rbs-inlineを導入してYARDからRBSに移行する
euglena1215
1
290
[DroidKaigi 2024] Android ViewからJetpack Composeへ 〜Jetpack Compose移行のすゝめ〜 / From Android View to Jetpack Compose: A Guide to Migration
syarihu
1
660
GenU導入でCDKに初挑戦し、悪戦苦闘した話
hideg
0
170
Scala アプリケーションのビルドを改善してデプロイ時間を 1/4 にした話 | How I improved the build of my Scala application and reduced deployment time by 4x
nomadblacky
1
180
Findy - エンジニア向け会社紹介 / Findy Letter for Engineers
findyinc
4
90k
How to Break into Reading Open Source
kaspth
2
220
Rubyのobject_id
qnighy
6
1.3k
私のEbitengineの第一歩
qt_luigi
0
450
Method Swizzlingを行うライブラリにおけるマルチモジュール設計
yoshikma
0
120
Featured
See All Featured
A better future with KSS
kneath
235
17k
Keith and Marios Guide to Fast Websites
keithpitt
408
22k
VelocityConf: Rendering Performance Case Studies
addyosmani
322
23k
What’s in a name? Adding method to the madness
productmarketing
PRO
21
3k
Learning to Love Humans: Emotional Interface Design
aarron
270
40k
Fireside Chat
paigeccino
31
2.9k
The Invisible Side of Design
smashingmag
296
50k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
24
610
Reflections from 52 weeks, 52 projects
jeffersonlam
346
20k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
248
20k
Intergalactic Javascript Robots from Outer Space
tanoku
268
26k
Into the Great Unknown - MozCon
thekraken
29
1.4k
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
[email protected]