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
iOSエンジニアから始める visionOS アプリ開発
nao_randd
3
120
ISUCON14公式反省会LT: 社内ISUCONの話
astj
PRO
0
180
[JAWS-UG横浜 #79] re:Invent 2024 の DB アップデートは Multi-Region!
maroon1st
1
140
Pulsar2 を雰囲気で使ってみよう
anoken
0
230
Kanzawa.rbのLT大会を支える技術の裏側を変更する Ruby on Rails + Litestream 編
muryoimpl
0
220
動作確認やテストで漏れがちな観点3選
starfish719
6
1k
Honoをフロントエンドで使う 3つのやり方
yusukebe
4
2.1k
Grafana Loki によるサーバログのコスト削減
mot_techtalk
1
110
Lottieアニメーションをカスタマイズしてみた
tahia910
0
120
CNCF Project の作者が考えている OSS の運営
utam0k
5
690
TokyoR116_BeginnersSession1_環境構築
kotatyamtema
0
110
Immutable ActiveRecord
megane42
0
130
Featured
See All Featured
Rails Girls Zürich Keynote
gr2m
94
13k
Navigating Team Friction
lara
183
15k
The Language of Interfaces
destraynor
156
24k
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
Designing Experiences People Love
moore
139
23k
VelocityConf: Rendering Performance Case Studies
addyosmani
328
24k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
49
2.3k
A Tale of Four Properties
chriscoyier
158
23k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.3k
Making Projects Easy
brettharned
116
6k
Build The Right Thing And Hit Your Dates
maggiecrowley
34
2.5k
The Power of CSS Pseudo Elements
geoffreycrofte
75
5.5k
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]