SlideShare ist ein Scribd-Unternehmen logo
1 von 16
namespace design
pattern para jQuery
     Diego Fleury - Junho 2010
   http://www.diegofleury.com.br
   http://twitter.com/diegofleury
o que conhecemos

padrão de projetos default para escrever um plugin
               baseado no seletor
jQuery.fn.myPlugin = function() {
 return this.each(function() {
   // Faz algo com cada elemento
 });
};
problemas

• Conflito de nome
• Plugins grandes precisarão de outros meios
  para se organizarem
• Comunicação e compartilhamento de
  dados entre partes menores do mesmo
  plugin fica dificultada
conflito de nomes
validate, valid, removeAttrs, form, element,
resetForm, showErrors, required, remote,
minlength, maxlength, email, url, date, number

 Os nomes genéricos podem causar dores de
    cabeça, troca de plugins e desistência.
plugins grandes

• Plugins maiores precisam ser divididos em
  partes
• Alternativa como no jQuery UI
     $(“foo”).bar(“myAction”, “myArgument”);


• Programação orientada a eventos
   $(“foo”).trigger(“myAction”, [“myArgument”]);
comunicação das partes

• Contextos muito permissivos (globais)
• Exposição (sem encapsulamento)
• Excesso de parametrização
opções atuais

• Continuar como está
• Utilizar as alternativas já apresentadas
• Plugins de namespace
plugins de namespace

• Preço alto a ser pago
• Soluções experimentais
• Muito longe do natural
Object Augmentation


• Simples    var foo = {};
• Flexível   foo.bar = “baz”;
jQuery namespace
     pattern
$.fn.MyPlugin = function() {

     this.firstMethod = function() {
         return this.each(function() {
             "This method persists the namespaced chain";
         });
     };

     return this; // Returns the jQuery's modified object

};



$(“foo”).MyPlugin(); // returns namespaced jQuery object

$(“foo”).MyPlugin().firstMethod(); // returns namespaced jQuery object

$(“foo”).MyPlugin().firstMethod().hide(); // returns namespaced jQuery object

$(“foo”).firstMethod(); // Error: firstMethod is not a function
interropendo a chain
         com namespace
$.fn.MyPlugin = function() {

     this.firstMethod = function() {
         return this.each(function() {
             "This method persists the namespaced chain";
         });
     };

     this.secondMethod = function() {                           Isto serve para casos
         return $(this.each(function() {                           específicos onde
             "This method persists the namespaced chain";         queremos forçar a
         }));                                                utilização do namespace a
     };                                                             cada invocação
     return this; // Returns the jQuery's modified object

};



$(“foo”).MyPlugin().secondMethod().hide(); // Pure jQuery object

$(“foo”).MyPlugin().firstMethod().secondMethod(); // Pure jQuery object

$(“foo”).MyPlugin().secondMethod().firstMethod(); // firstMethod is not a function
otimizando
(function() {

    $.fn.MyPlugin = function() {

         this.firstMethod = parts.firstMethod;
         this.secondMethod = parts.secondMethod;

         return this; // Returns the jQuery's modified object

    };                                                             Agora, só fazemos
                                                                referência há funções já
    var parts = {                                                   construídas pelo
         firstMethod: function() {                              interpretador JavaScript
             return this.each(function() {                        ao executar a função
                 "This method persists the namespaced chain";    anônima mais externa
             });
         },

         secondMethod: function() {
             return $(this.each(function() {
                 "This method persists the namespaced chain";
             }));
         }

    };

})();
opções globais
(function() {

    var parts, globalOptions = {foo: “default”};
                                                            Isso pode ser bem útil
    $.fn.MyPlugin = function(globalConfig) {

         $.extend(globalOptions, globalConfig);

         this.firstMethod = parts.firstMethod;
         this.secondMethod = parts.secondMethod;

         return this; // Returns the jQuery's modified object

    };

    parts = {

         firstMethod: function(config) {

              var options = $.extend({}, globalOptions, config);

              return this.each(function() {
                  "This method persists the namespaced chain";
              });
         },

         secondMethod: function() { /* ... */ }

    };                                               $(“foo”)
                                                         .MyPlugin({foo: “global”})
})();                                                        .firstMethod({foo: “especific”});
muitos métodos
(function() {

    var parts, globalOptions = {foo: “default”};         Recomendo fazer isso
    $.fn.MyPlugin = function(globalConfig) {            somente quando houver
         $.extend(globalOptions, globalConfig);
                                                         muitos métodos. Essa
                                                           operação é cara.
         $.extend(this, parts);

         return this; // Returns the jQuery's modified object

    };

    parts = {

         firstMethod: function(config) {

              var options = $.extend({}, globalOptions, config);

              return this.each(function() {
                  "This method persists the namespaced chain";
              });
         },

         secondMethod: function() { /* ... */ }

    };

})();
Vantagens

• Organização
• Simples de empregar
• Natural
• Parametrização global
  “This is nice - it's a simple pattern to employ, for sure.”
                                                    - John Resig

Weitere ähnliche Inhalte

Andere mochten auch

2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
Yevgeny Sinyakov
 
Paintball 23 03 08
Paintball 23 03 08Paintball 23 03 08
Paintball 23 03 08
arabacamp
 
Nettvett og personvern
Nettvett og personvernNettvett og personvern
Nettvett og personvern
Ellen Skaadel
 

Andere mochten auch (16)

Building an app-like experience (without the app)
Building an app-like experience (without the app)Building an app-like experience (without the app)
Building an app-like experience (without the app)
 
Zoom in on Hermitage
Zoom in on HermitageZoom in on Hermitage
Zoom in on Hermitage
 
2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
2013 ТРИУНА Лидерз, Колесо Инноваций, презентация книги
 
Mem·or·y
Mem·or·yMem·or·y
Mem·or·y
 
今日からはじめる「じぶんブランディング」
今日からはじめる「じぶんブランディング」今日からはじめる「じぶんブランディング」
今日からはじめる「じぶんブランディング」
 
At
AtAt
At
 
Learning Designs For Constructivist Pedagogy
Learning Designs For Constructivist PedagogyLearning Designs For Constructivist Pedagogy
Learning Designs For Constructivist Pedagogy
 
持続可能な教材開発プロジェクトのために教師がWebですべきこと
持続可能な教材開発プロジェクトのために教師がWebですべきこと持続可能な教材開発プロジェクトのために教師がWebですべきこと
持続可能な教材開発プロジェクトのために教師がWebですべきこと
 
Paintball 23 03 08
Paintball 23 03 08Paintball 23 03 08
Paintball 23 03 08
 
Leeds inventors group
Leeds inventors groupLeeds inventors group
Leeds inventors group
 
Connecticut Goes Red For Women
Connecticut Goes Red For WomenConnecticut Goes Red For Women
Connecticut Goes Red For Women
 
Nettvett og personvern
Nettvett og personvernNettvett og personvern
Nettvett og personvern
 
Rochester Goes Red For Women
Rochester Goes Red For WomenRochester Goes Red For Women
Rochester Goes Red For Women
 
How the law protects investment in technology - trade secrets, patents, desig...
How the law protects investment in technology - trade secrets, patents, desig...How the law protects investment in technology - trade secrets, patents, desig...
How the law protects investment in technology - trade secrets, patents, desig...
 
Enforcement
EnforcementEnforcement
Enforcement
 
East Amsterdam? Of Course Together!
East Amsterdam? Of Course Together!East Amsterdam? Of Course Together!
East Amsterdam? Of Course Together!
 

Kürzlich hochgeladen

Kürzlich hochgeladen (6)

ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemplo
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object Calisthenics
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
 

jQuery Namespace Design Pattern (PT-BR)

  • 1. namespace design pattern para jQuery Diego Fleury - Junho 2010 http://www.diegofleury.com.br http://twitter.com/diegofleury
  • 2. o que conhecemos padrão de projetos default para escrever um plugin baseado no seletor jQuery.fn.myPlugin = function() { return this.each(function() { // Faz algo com cada elemento }); };
  • 3. problemas • Conflito de nome • Plugins grandes precisarão de outros meios para se organizarem • Comunicação e compartilhamento de dados entre partes menores do mesmo plugin fica dificultada
  • 4. conflito de nomes validate, valid, removeAttrs, form, element, resetForm, showErrors, required, remote, minlength, maxlength, email, url, date, number Os nomes genéricos podem causar dores de cabeça, troca de plugins e desistência.
  • 5. plugins grandes • Plugins maiores precisam ser divididos em partes • Alternativa como no jQuery UI $(“foo”).bar(“myAction”, “myArgument”); • Programação orientada a eventos $(“foo”).trigger(“myAction”, [“myArgument”]);
  • 6. comunicação das partes • Contextos muito permissivos (globais) • Exposição (sem encapsulamento) • Excesso de parametrização
  • 7. opções atuais • Continuar como está • Utilizar as alternativas já apresentadas • Plugins de namespace
  • 8. plugins de namespace • Preço alto a ser pago • Soluções experimentais • Muito longe do natural
  • 9. Object Augmentation • Simples var foo = {}; • Flexível foo.bar = “baz”;
  • 10. jQuery namespace pattern
  • 11. $.fn.MyPlugin = function() { this.firstMethod = function() { return this.each(function() { "This method persists the namespaced chain"; }); }; return this; // Returns the jQuery's modified object }; $(“foo”).MyPlugin(); // returns namespaced jQuery object $(“foo”).MyPlugin().firstMethod(); // returns namespaced jQuery object $(“foo”).MyPlugin().firstMethod().hide(); // returns namespaced jQuery object $(“foo”).firstMethod(); // Error: firstMethod is not a function
  • 12. interropendo a chain com namespace $.fn.MyPlugin = function() { this.firstMethod = function() { return this.each(function() { "This method persists the namespaced chain"; }); }; this.secondMethod = function() { Isto serve para casos return $(this.each(function() { específicos onde "This method persists the namespaced chain"; queremos forçar a })); utilização do namespace a }; cada invocação return this; // Returns the jQuery's modified object }; $(“foo”).MyPlugin().secondMethod().hide(); // Pure jQuery object $(“foo”).MyPlugin().firstMethod().secondMethod(); // Pure jQuery object $(“foo”).MyPlugin().secondMethod().firstMethod(); // firstMethod is not a function
  • 13. otimizando (function() { $.fn.MyPlugin = function() { this.firstMethod = parts.firstMethod; this.secondMethod = parts.secondMethod; return this; // Returns the jQuery's modified object }; Agora, só fazemos referência há funções já var parts = { construídas pelo firstMethod: function() { interpretador JavaScript return this.each(function() { ao executar a função "This method persists the namespaced chain"; anônima mais externa }); }, secondMethod: function() { return $(this.each(function() { "This method persists the namespaced chain"; })); } }; })();
  • 14. opções globais (function() { var parts, globalOptions = {foo: “default”}; Isso pode ser bem útil $.fn.MyPlugin = function(globalConfig) { $.extend(globalOptions, globalConfig); this.firstMethod = parts.firstMethod; this.secondMethod = parts.secondMethod; return this; // Returns the jQuery's modified object }; parts = { firstMethod: function(config) { var options = $.extend({}, globalOptions, config); return this.each(function() { "This method persists the namespaced chain"; }); }, secondMethod: function() { /* ... */ } }; $(“foo”) .MyPlugin({foo: “global”}) })(); .firstMethod({foo: “especific”});
  • 15. muitos métodos (function() { var parts, globalOptions = {foo: “default”}; Recomendo fazer isso $.fn.MyPlugin = function(globalConfig) { somente quando houver $.extend(globalOptions, globalConfig); muitos métodos. Essa operação é cara. $.extend(this, parts); return this; // Returns the jQuery's modified object }; parts = { firstMethod: function(config) { var options = $.extend({}, globalOptions, config); return this.each(function() { "This method persists the namespaced chain"; }); }, secondMethod: function() { /* ... */ } }; })();
  • 16. Vantagens • Organização • Simples de empregar • Natural • Parametrização global “This is nice - it's a simple pattern to employ, for sure.” - John Resig

Hinweis der Redaktion