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
Organizando o JavaScript (WebDay 2013)
Search
Nando Vieira
July 20, 2013
Programming
1.2k
20
Share
Organizando o JavaScript (WebDay 2013)
Palestra apresentada no WebDay 2013
Nando Vieira
July 20, 2013
More Decks by Nando Vieira
See All by Nando Vieira
Permanecendo Relevante
fnando
9
1.5k
O que mudou no Rails 5
fnando
3
580
Porque usar PostgreSQL (Se você ainda não o faz)
fnando
25
3.1k
Criando aplicações web mais seguras
fnando
4
700
Criando aplicações mais fáceis de manter com Ruby on Rails
fnando
35
2.1k
Conhecendo Variants do Rails 4.1
fnando
11
600
JavaScript Funcional
fnando
36
1.8k
Segurança em Aplicações Web
fnando
31
3.1k
Segurança no Rails
fnando
20
970
Other Decks in Programming
See All in Programming
tRPCの概要と少しだけパフォーマンス
misoton665
2
260
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
200
AI時代のエンジニアリングの原則 / Engineering Principles in the AI Era
haru860
0
1.1k
継続的な負荷検証を目指して
pyama86
0
330
【26新卒研修】OpenAPI/Swagger REST API研修
dip_tech
PRO
0
140
Are We Really Coding 10× Faster with AI?
kohzas
0
110
Firefoxにコントリビューションして得られた学び
ken7253
2
150
エラー処理の温故知新 / history of error handling technic
ryotanakaya
7
1.8k
Agent Skills を社内で育てる仕組み作り
jackchuka
1
1.5k
実践ハーネスエンジニアリング:ステアリングループを実例から読み解く / Practical Harness Engineering: Understanding Steering Loops Through Real-World Examples
nrslib
5
4.2k
空間オーディオの活用
objectiveaudio
0
140
Surviving Black Friday: 329 billion requests with Falcon!
ioquatix
0
2.8k
Featured
See All Featured
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
0
1.3k
The Language of Interfaces
destraynor
162
26k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.7k
State of Search Keynote: SEO is Dead Long Live SEO
ryanjones
0
190
Designing for Timeless Needs
cassininazir
0
220
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.4k
We Have a Design System, Now What?
morganepeng
55
8.1k
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
290
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
340
For a Future-Friendly Web
brad_frost
183
10k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.5k
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
170
Transcript
Or anizando o JavaScript Nando Vieira
Nando Vieira http://simplesideias.com.br @fnando
hellobits.com empresa
howtocode.com.br cursos
codeplane.com.br it hostin
* * *
O JavaScript passou por al umas revoluções durante o seu
tempo de vida.
2004 Primeira revolução Goo le lançou o Gmail com uso
de AJAX
2006 Se unda revolução John Resi lançou o jQuery em
um meetup em NY.
2009 Terceira revolução Ryan Dahl lançou o Node.js
O JavaScript é a lin ua em mais importante da
atualidade.
Dos 50 repositórios mais populares do Github, 29 repositórios são
relacionados a JavaScript.
O JavaScript já tem quase 20 anos de idade.
Por que a ente ainda escreve códi os ruins?
"invite_friends" : function() { var resizeLoader = function() { $("#loader").css("width",
$(".places").width()); $("#loader").css("height", $(".places").height()-18); } resizeLoader(); var resizeTimer; $(window).bind('resize', function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(resizeLoader, 50); }); $("a[href=#automatic_invite]").click(function(e){ SomeApp.utils.stopPropagation(e); if(!$(this).parents(".tab_title:first").is(".active")) { $(".tab_title:first") .toggleClass("active"); $(".tab_title:last") .toggleClass("active"); $("#automatic") .toggleClass("hidden"); $("#manual") .toggleClass("hidden"); } }); var suffixes = { "gmail": "@gmail.com", "yahoo": "", "live": "@hotmail.com", "other": ""
A solução é modularidade.
Só a modularidade permitirá separar as responsabilidades do seu códi
o.
Só a modularidade tornará possível expandir o seu códi o
com facilidade.
Só a modularidade tornará possível a manutenção do seu codebase.
De quebra você ainda anha reusabilidade de componentes.
E é somente assim que o seu códi o poderá
ser testado sem dificuldades.
Se temos todos esses benefícios, porque ainda não escrevemos códi
os dessa maneira?
A verdade é que a maioria dos desenvolvedores não sabe
como fazer isso.
E porque escrever códi os modulares pode ser difícil.
Então, como fazer?
Conhecimento
Conheça a lin ua em.
http://developer.mozilla.or
http://howtocode.com.br
http://w3scho… melhor não!
http://w3fools.com
Or anização
Pense no seu códi o como uma série de blocos
que precisam encaixar uns nos outros.
None
None
None
None
None
None
Muitos outros componentes serão criados à partir dessa estrutura.
Pense em como esses blocos irão se comunicar através de
uma API pública.
Não referencie objetos diretamente do DOM, nem acesse outros objetos
lobais.
Passe todas as dependências como ar umentos da função construtora.
Cada um desses blocos pode ter o seu próprio arquivo.
É melhor ter muitos arquivos pequenos do que poucos arquivos
randes.
javascripts application.js eden AddToRe istry.js ProductInfo.js modules UserRe istries.js addToCartModule.js
addressListModule.js boletoModule.js cartReviewModule.js cate oryInterests.js cate oryModule.js checkoutModule.js
Lembre-se que você sempre pode concatenar e minificar o seu
códi o antes de colocar em produção.
Modularização
O JavaScript possui al umas alternativas diferentes para a criação
de módulos.
Você pode utilizar a ideia de namespaces com object literals.
var Todo = { tasks: [] , addTask: function(task) {}
, removeTask : function() {} , count : function() {} };
Object literals são muitos simples de utilizar, mas se comportam
mais como sin letons.
O Module pattern permite simular a escopo e visibilidade de
atributos.
var Todo = (function(){ var tasks = []; // private
variable // expose the public API return { addTask: function(task) {} , removeTask: function(task) {} , count: function() {} }; })();
O Module pattern também permite fazer a injeção de dependências.
var Todo = (function($, hb){ // all your code here
})(jQuery, Handlebars);
Eu costumo usar uma variação de Module pattern com namespace.
Module("MyApp.MyModule", function(MyModule){ MyModule.fn.initialize = function() { // this is the
initializer }; MyModule.fn.someFunction = function() { // fn is just shortcut for // prototype alas jQuery }; });
http:// ithub.com/fnando/module.js
Dependência entre os módulos não é um problema.
Utilize a aborda em sin le entry point.
// boot.js $(function(){ var html = $("html") , controller =
html.data("controller") , action = html.data("action") ; MyApp.Application(controller, action); });
Existem outras alternativas de módulos como AMD e CommonJS.
Já existe um draft de módulos nativos no JavaScript no
ES6 Harmony.
module Todo { var tasks = []; // private variable
// expose the public API export default { addTask: function(task) {} , removeTask: function(task) {} , count: function() {} }; }
module Todo { var tasks = []; // private variable
// expose the public API export default { addTask: function(task) {} , removeTask: function(task) {} , count: function() {} }; }
import Todo from Todo; Todo.addTask(task);
Os módulos podem ser importados através de URLs.
// load from remote sources module $ from "http://example.org/jquery.js"; //
Module loader API Loader.load("http://example.org/jquery.js", function($){ // do what you need });
Você pode ser específico sobre o que quer importar.
import { a, b, c } from "some/file";
Ainda está em discussão. http://fnando.me/jp
Exemplo
Vamos implementar um postbox. http://fnando.me/jq
None
Primeiro implemente a funcionalidade do jeito mais rápido, para entender
o problema.
$(".postbox textarea") .on("focus", function(){ $(this).closest(".postbox") .addClass("did-focus") .removeClass("is-contracted") ; }) .on("keyup",
function(){ var lines = this.value.split(/\r?\n/); var textarea = $(this); if (lines.length >= 5) { textarea.addClass("is-taller"); } else { textarea.removeClass("is-taller"); } }) .on("blur", function(){ if (!this.value) { $(this).closest(".postbox").addClass("is-contracted"); } }) ;
$(".postbox textarea") .on("focus", function(){ $(this).closest(".postbox") .addClass("did-focus") .removeClass("is-contracted") ; }) .on("keyup",
function(){ var lines = this.value.split(/\r?\n/); var textarea = $(this); if (lines.length >= 5) { textarea.addClass("is-taller"); } else { textarea.removeClass("is-taller"); } }) .on("blur", function(){ if (!this.value) { $(this).closest(".postbox").addClass("is-contracted"); } }) ;
$(".postbox textarea") .on("focus", function(){ $(this).closest(".postbox") .addClass("did-focus") .removeClass("is-contracted") ; }) .on("keyup",
function(){ var lines = this.value.split(/\r?\n/); var textarea = $(this); if (lines.length >= 5) { textarea.addClass("is-taller"); } else { textarea.removeClass("is-taller"); } }) .on("blur", function(){ if (!this.value) { $(this).closest(".postbox").addClass("is-contracted"); } }) ;
$(".postbox textarea") .on("focus", function(){ $(this).closest(".postbox") .addClass("did-focus") .removeClass("is-contracted") ; }) .on("keyup",
function(){ var lines = this.value.split(/\r?\n/); var textarea = $(this); if (lines.length >= 5) { textarea.addClass("is-taller"); } else { textarea.removeClass("is-taller"); } }) .on("blur", function(){ if (!this.value) { $(this).closest(".postbox").addClass("is-contracted"); } }) ;
Depois que você conse uiu entender o problema, escreva uma
solução mais modular.
Module("HOWTO.Postbox", function(Postbox){ Postbox.fn.initialize = function(container) { this.container = container; this.textarea
= container.find(".pb-input"); this.button = container.find(".pb-button"); }; });
Module("HOWTO.Postbox", function(Postbox){ Postbox.fn.initialize = function(container) { // the initialization code
this.addEventListeners(); }; Postbox.fn.addEventListeners = function() { this.textarea .on("focus", this.onTextareaFocus.bind(this)) .on("keyup", this.onTextareaKeyUp.bind(this)) .on("blur", this.onTextareaBlur.bind(this)) ; }; });
Module("HOWTO.Postbox", function(Postbox){ Postbox.fn.initialize = function(container) {}; Postbox.fn.addEventListeners = function() {};
Postbox.fn.onTextareaFocus = function(event) { this.container .addClass("did-focus") .removeClass("is-contracted") ; }; });
Module("HOWTO.Postbox", function(Postbox){ Postbox.fn.initialize = function(container) {}; Postbox.fn.addEventListeners = function() {};
Postbox.fn.onTextareaFocus = function(event) {}; var LINES = 5; Postbox.fn.onTextareaKeyUp = function(event) { var lines = event.target.value.split(/\r?\n/); if (lines.length >= LINES) { this.textarea.addClass("is-taller"); } else { this.textarea.removeClass("is-taller"); } }; });
Module("HOWTO.Postbox", function(Postbox){ Postbox.fn.initialize = function(container) {}; Postbox.fn.addEventListeners = function() {};
Postbox.fn.onTextareaFocus = function(event) {}; Postbox.fn.onTextareaKeyUp = function(event) {}; Postbox.fn.onTextareaBlur = function(event) { if (!event.target.value) { this.container.addClass("is-contract"); } }; });
Sempre que você escreve códi os mais modulares, é muito
mais simples escrever testes.
describe("HOWTO.Postbox", function() { var container, postbox, textarea; beforeEach(function() { container
= $("<div/>") .append("<textarea class='pb-input'/>") .append("<button class='pb-button' value='Reply'/>") .appendTo("#sample") ; textarea = container.find("textarea"); postbox = HOWTO.Postbox(container); }); it("sets class when focusing box", function() { textarea.trigger("focus"); expect(container.is(".did-focus")).toBeTruthy(); }); // other specs });
Finalizando
Todo aplicativo complexo deve ser quebrado em pedaços menores.
Você nunca sabe qual vai ser o tamanho do seu
projeto.
Códi os modulares podem ser escritos sem o uso de
bibliotecas.
Mas use o que for melhor para o seu workflow.
Obri ado!
* * *
http://howtocode.com.br