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
Bedrock Agentsレスポンス解析によるAgentのOps
licux
2
720
Introduction to kotlinx.rpc
arawn
0
630
WebDriver BiDiとは何なのか
yotahada3
1
140
DevinとCursorから学ぶAIエージェントメモリーの設計とMoatの考え方
itarutomy
1
640
2024年のkintone API振り返りと2025年 / kintone API look back in 2024
tasshi
0
210
Kanzawa.rbのLT大会を支える技術の裏側を変更する Ruby on Rails + Litestream 編
muryoimpl
0
220
XStateを用いた堅牢なReact Components設計~複雑なClient Stateをシンプルに~ @React Tokyo ミートアップ #2
kfurusho
1
770
Pulsar2 を雰囲気で使ってみよう
anoken
0
230
CloudNativePGがCNCF Sandboxプロジェクトになったぞ! 〜CloudNativePGの仕組みの紹介〜
nnaka2992
0
220
自分ひとりから始められる生産性向上の取り組み #でぃーぷらすオオサカ
irof
8
2.6k
iOSエンジニアから始める visionOS アプリ開発
nao_randd
3
120
Amazon ECS とマイクロサービスから考えるシステム構成
hiyanger
2
490
Featured
See All Featured
Visualization
eitanlees
146
15k
Optimizing for Happiness
mojombo
376
70k
[RailsConf 2023] Rails as a piece of cake
palkan
53
5.2k
GraphQLとの向き合い方2022年版
quramy
44
13k
Producing Creativity
orderedlist
PRO
343
39k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
44
9.4k
A Philosophy of Restraint
colly
203
16k
Building Flexible Design Systems
yeseniaperezcruz
328
38k
What's in a price? How to price your products and services
michaelherold
244
12k
Faster Mobile Websites
deanohume
306
31k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
27
1.9k
The Art of Programming - Codeland 2020
erikaheidi
53
13k
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]