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
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