SlideShare a Scribd company logo
1 of 17
Download to read offline
JAVASCRIPT
NÃO-OBSTRUTIVO
    com jQuery


                 Por Marcelo Fraga
O QUE É?
Um conjunto de princípios para uma escrita de
  JavaScript acessível, de fácil manutenção.
CARACTERÍSTICAS
• Sempre aplicar JavaScript em arquivos externos.
• Nunca utilizar JavaScript diretamente no documento.
• Usar JavaScript como incremento, não como uma funcionalidade segura.
• A página continua sendo utilizável, mesmo sem o suporte a JavaScript.
EXEMPLO
Uma vez que a página foi carregada, o JavaScript:

• Encontra todos os labels ligados a um campo de texto.
• Move o texto do label para o campo de texto associado.
• Esconde os labels.
• Estabelece eventos para remover o texto descritivo quando o campo está em foco.
EXEMPLO
O JAVASCRIPT
$('label').each(function() {
	

 var $label = $(this),
	

       $input = $('#' + $label.attr('for')),
	

       initial = $label.hide().text();
	

 $input.focus(function() {
	

 	

 if ($input.val() == initial) {
	

 	

 	

 $input.val(‘’).css('color', '#000');
	

 	

 }
	

 }).blur(function() {
	

 	

 if (!$input.val()) {
	

 	

 	

 $input.val(initial).css('color', '#aaa');
	

 	

 }
	

 }).css('color', '#aaa').val(initial);
});
O HTML
<form action=”procurar.php”>
    <label for=”procurar”>Procurar</label>
    <input type=”text” id=”procurar” name=”procurar” />
    <button type=”submit”>ok</button>
</form>
MAL USO
<a href=”javascript: window.open(‘http://zigotto.com.br’);”>Zigotto</a>
MAL USO
<a href=”#” onclick=”javascript: window.open(‘http://zigotto.com.br’); return false;”>Zigotto</a>
UM POUCO MELHOR
<a href=”http://zigotto.com.br” onclick=”javascript: window.open(this.href); return
false;”>Zigotto</a>
O MELHOR
<a href=”http://zigotto.com.br” rel=”externo”>Zigotto</a>


          $('a[rel="externo"]').click(function(e) {
              window.open(this.href);
              e.preventDefault();
          });
A IMPLEMENTAÇÃO
               GARBER-IRISH
<body data-controller=”<%= params[:controller] %>” data-action=”<%= params[:action] %>”>
A IMPLEMENTAÇÃO
   GARBER-IRISH
   <body id=”cart” class=”shopping”>
A IMPLEMENTAÇÃO
   GARBER-IRISH
     SITENAME = {
        common: {
           init: function() {
               // code
           }
        },
        users: {
           init: function() {
               // code
           },
           show: function() {
               // code
           }
        }
     };
A IMPLEMENTAÇÃO
                  GARBER-IRISH
UTIL = {
  exec: function(controller, action) {
      var namespace = SITENAME,
          action     = (action === undefined) ? “init” : action;

         if (controller && namespace[controller] && typeof(namespace[controller][action] == “function”)) {
              namespace[controller][action]();
         }
     },
     init: function() {
          var $body = $(document.body),
              controller = $body.data(‘controller’),
              action    = $body.data(‘action’);

         UTIL.exec(‘common’);
         UTIL.exec(controller);
         UTL.exec(controller, action);
     }
};
A IMPLEMENTAÇÃO
   GARBER-IRISH
    $(document).ready(UTIL.init);
FONTES
• http://dev.opera.com/articles/view/the-seven-rules-of-unobtrusive-javascrip/
• http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-
execution/
• http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-
execution

More Related Content

What's hot

Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Cirdes Filho
 
How to develop modern web application framework
How to develop modern web application frameworkHow to develop modern web application framework
How to develop modern web application frameworktechmemo
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方techmemo
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리태준 김
 
PerlでWeb API入門
PerlでWeb API入門PerlでWeb API入門
PerlでWeb API入門Yusuke Wada
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015Matheus Marabesi
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...Matheus Marabesi
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingJace Ju
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Dotan Dimet
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Matheus Marabesi
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hopeMarcus Ramberg
 

What's hot (20)

Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
 
How to develop modern web application framework
How to develop modern web application frameworkHow to develop modern web application framework
How to develop modern web application framework
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리
 
RSpec
RSpecRSpec
RSpec
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Excellent
ExcellentExcellent
Excellent
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
PerlでWeb API入門
PerlでWeb API入門PerlでWeb API入門
PerlでWeb API入門
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Session8
Session8Session8
Session8
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Mojolicious on Steroids
Mojolicious on SteroidsMojolicious on Steroids
Mojolicious on Steroids
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 

Viewers also liked

Viewers also liked (7)

Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Desvendando a Web - Ponto de vista de um Zigottiano
Desvendando a Web - Ponto de vista de um ZigottianoDesvendando a Web - Ponto de vista de um Zigottiano
Desvendando a Web - Ponto de vista de um Zigottiano
 
Engine on Rails
Engine on RailsEngine on Rails
Engine on Rails
 
Testes de aceitação com Steak e Capybara
Testes de aceitação com Steak e CapybaraTestes de aceitação com Steak e Capybara
Testes de aceitação com Steak e Capybara
 
Sinatra - Primeiros Passos
Sinatra - Primeiros PassosSinatra - Primeiros Passos
Sinatra - Primeiros Passos
 
Um pouco de Agile
Um pouco de AgileUm pouco de Agile
Um pouco de Agile
 
Ilustrações, técnicas e formas
Ilustrações, técnicas e formasIlustrações, técnicas e formas
Ilustrações, técnicas e formas
 

Similar to JavaScript não-obstrutivo com jQuery

Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Chris Alfano
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegapyangdj
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaveryangdj
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshowsblackman
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...PHP Conference Argentina
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiPraveen Puglia
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 

Similar to JavaScript não-obstrutivo com jQuery (20)

Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegap
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 

More from Zigotto Tecnologia

Usando QUnit para testes unitários em JavaScript
Usando QUnit para testes unitários em JavaScriptUsando QUnit para testes unitários em JavaScript
Usando QUnit para testes unitários em JavaScriptZigotto Tecnologia
 
Nova API do Google Maps e Possíveis Aplicações
Nova API do Google Maps e Possíveis AplicaçõesNova API do Google Maps e Possíveis Aplicações
Nova API do Google Maps e Possíveis AplicaçõesZigotto Tecnologia
 
Apps para SmartPhones usando PhoneGap
Apps para SmartPhones usando PhoneGapApps para SmartPhones usando PhoneGap
Apps para SmartPhones usando PhoneGapZigotto Tecnologia
 

More from Zigotto Tecnologia (7)

Apresentação Padawan
Apresentação PadawanApresentação Padawan
Apresentação Padawan
 
Open Source - DevInVale 2011
Open Source - DevInVale 2011Open Source - DevInVale 2011
Open Source - DevInVale 2011
 
Escrevendo plugins JQuery
Escrevendo plugins JQueryEscrevendo plugins JQuery
Escrevendo plugins JQuery
 
HTML5
HTML5HTML5
HTML5
 
Usando QUnit para testes unitários em JavaScript
Usando QUnit para testes unitários em JavaScriptUsando QUnit para testes unitários em JavaScript
Usando QUnit para testes unitários em JavaScript
 
Nova API do Google Maps e Possíveis Aplicações
Nova API do Google Maps e Possíveis AplicaçõesNova API do Google Maps e Possíveis Aplicações
Nova API do Google Maps e Possíveis Aplicações
 
Apps para SmartPhones usando PhoneGap
Apps para SmartPhones usando PhoneGapApps para SmartPhones usando PhoneGap
Apps para SmartPhones usando PhoneGap
 

JavaScript não-obstrutivo com jQuery

  • 1. JAVASCRIPT NÃO-OBSTRUTIVO com jQuery Por Marcelo Fraga
  • 2. O QUE É? Um conjunto de princípios para uma escrita de JavaScript acessível, de fácil manutenção.
  • 3. CARACTERÍSTICAS • Sempre aplicar JavaScript em arquivos externos. • Nunca utilizar JavaScript diretamente no documento. • Usar JavaScript como incremento, não como uma funcionalidade segura. • A página continua sendo utilizável, mesmo sem o suporte a JavaScript.
  • 4. EXEMPLO Uma vez que a página foi carregada, o JavaScript: • Encontra todos os labels ligados a um campo de texto. • Move o texto do label para o campo de texto associado. • Esconde os labels. • Estabelece eventos para remover o texto descritivo quando o campo está em foco.
  • 6. O JAVASCRIPT $('label').each(function() { var $label = $(this), $input = $('#' + $label.attr('for')), initial = $label.hide().text(); $input.focus(function() { if ($input.val() == initial) { $input.val(‘’).css('color', '#000'); } }).blur(function() { if (!$input.val()) { $input.val(initial).css('color', '#aaa'); } }).css('color', '#aaa').val(initial); });
  • 7. O HTML <form action=”procurar.php”> <label for=”procurar”>Procurar</label> <input type=”text” id=”procurar” name=”procurar” /> <button type=”submit”>ok</button> </form>
  • 8. MAL USO <a href=”javascript: window.open(‘http://zigotto.com.br’);”>Zigotto</a>
  • 9. MAL USO <a href=”#” onclick=”javascript: window.open(‘http://zigotto.com.br’); return false;”>Zigotto</a>
  • 10. UM POUCO MELHOR <a href=”http://zigotto.com.br” onclick=”javascript: window.open(this.href); return false;”>Zigotto</a>
  • 11. O MELHOR <a href=”http://zigotto.com.br” rel=”externo”>Zigotto</a> $('a[rel="externo"]').click(function(e) { window.open(this.href); e.preventDefault(); });
  • 12. A IMPLEMENTAÇÃO GARBER-IRISH <body data-controller=”<%= params[:controller] %>” data-action=”<%= params[:action] %>”>
  • 13. A IMPLEMENTAÇÃO GARBER-IRISH <body id=”cart” class=”shopping”>
  • 14. A IMPLEMENTAÇÃO GARBER-IRISH SITENAME = { common: { init: function() { // code } }, users: { init: function() { // code }, show: function() { // code } } };
  • 15. A IMPLEMENTAÇÃO GARBER-IRISH UTIL = { exec: function(controller, action) { var namespace = SITENAME, action = (action === undefined) ? “init” : action; if (controller && namespace[controller] && typeof(namespace[controller][action] == “function”)) { namespace[controller][action](); } }, init: function() { var $body = $(document.body), controller = $body.data(‘controller’), action = $body.data(‘action’); UTIL.exec(‘common’); UTIL.exec(controller); UTL.exec(controller, action); } };
  • 16. A IMPLEMENTAÇÃO GARBER-IRISH $(document).ready(UTIL.init);