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
Immutable ActiveRecord
megane42
0
140
JavaScriptツール群「UnJS」を5分で一気に駆け巡る!
k1tikurisu
9
1.8k
Writing documentation can be fun with plugin system
okuramasafumi
0
120
楽しく向き合う例外対応
okutsu
0
150
チームリードになって変わったこと
isaka1022
0
200
Pulsar2 を雰囲気で使ってみよう
anoken
0
240
昭和の職場からアジャイルの世界へ
kumagoro95
1
380
『GO』アプリ バックエンドサーバのコスト削減
mot_techtalk
0
150
XStateを用いた堅牢なReact Components設計~複雑なClient Stateをシンプルに~ @React Tokyo ミートアップ #2
kfurusho
1
910
Amazon S3 TablesとAmazon S3 Metadataを触ってみた / 20250201-jawsug-tochigi-s3tables-s3metadata
kasacchiful
0
170
Lottieアニメーションをカスタマイズしてみた
tahia910
0
130
Software Architecture
hschwentner
6
2.1k
Featured
See All Featured
A Tale of Four Properties
chriscoyier
158
23k
Building Adaptive Systems
keathley
40
2.4k
Become a Pro
speakerdeck
PRO
26
5.1k
Documentation Writing (for coders)
carmenintech
67
4.6k
Fashionably flexible responsive web design (full day workshop)
malarkey
406
66k
Intergalactic Javascript Robots from Outer Space
tanoku
270
27k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
133
33k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
7k
Making Projects Easy
brettharned
116
6k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
248
1.3M
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
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]