SlideShare une entreprise Scribd logo
1  sur  16
namespace design
pattern for jQuery
     Diego Fleury - June 2010
  http://www.diegofleury.com.br
  http://twitter.com/diegofleury
what we know


design pattern default to write a selector based plugin

jQuery.fn.myPlugin = function() {
 return this.each(function() {
   // Do something with each element
 });
};
problems

• Name conflict
• Big plugins need other means to organize
• Communication and data share between
  smaller parts is harder
name conflict
validate, valid, removeAttrs, form, element,
resetForm, showErrors, required, remote,
minlength, maxlength, email, url, date, number

Generic names can cause headaches, change of
             plugins and desist
plugins grandes

• Bigger plugins must be sliced into parts
• Alternatively as in jQuery UI
      $(“foo”).bar(“myAction”, “myArgument”);


• Event-driven programming
   $(“foo”).trigger(“myAction”, [“myArgument”]);
communicaty of parts

• Contexts too 
permissive (globals)
• Exposure (no encapsulation)
• Over-parametrization
current options

• Continue as
• Use existing alternatives
• Namespace plugins
namespace plugins

• Expensive price to be paid
• Experimental solutions
• Far from natural
Object Augmentation


• Simple     var foo = {};
• Flexible   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
Stopping the
             namespace chain
$.fn.MyPlugin = function() {

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

     this.secondMethod = function() {                          This serves to specific
         return $(this.each(function() {                      cases where we want to
             "This method persists the namespaced chain";       force the use of the
         }));                                                    namespace to each
     };                                                              invocation
     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
optimizing
(function() {

    $.fn.MyPlugin = function() {

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

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

    };                                                           Now, we only reference
                                                                for functions already built
    var parts = {                                                    by the JavaScript
         firstMethod: function() {                                interpreter to execute
             return this.each(function() {                         the outer anonymous
                 "This method persists the namespaced chain";            function
             });
         },

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

    };

})();
global options
(function() {

    var parts, globalOptions = {foo: “default”};
                                                           This can be very useful
    $.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”});
many methods
(function() {

    var parts, globalOptions = {foo: “default”};         I recommend doing this
    $.fn.MyPlugin = function(globalConfig) {               only when there are
         $.extend(globalOptions, globalConfig);
                                                            many methods. This
                                                          operation is expensive.
         $.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() { /* ... */ }

    };

})();
Advantages

• Organization
• Simple to employ
• Natural
• Global parameterization
  “This is nice - it's a simple pattern to employ, for sure.”
                                                    - John Resig

Contenu connexe

Tendances

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Love and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayLove and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayKris Wallsmith
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareKuan Yen Heng
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeRebecca Murphey
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0Eyal Vardi
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 

Tendances (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Love and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayLove and Loss: A Symfony Security Play
Love and Loss: A Symfony Security Play
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middleware
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Matters of State
Matters of StateMatters of State
Matters of State
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Twig tips and tricks
Twig tips and tricksTwig tips and tricks
Twig tips and tricks
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 

En vedette

Hug Concepts Content Processes
Hug Concepts Content ProcessesHug Concepts Content Processes
Hug Concepts Content Processessrenshaw
 
Introduction to IP: Useful Websites
Introduction to IP: Useful WebsitesIntroduction to IP: Useful Websites
Introduction to IP: Useful WebsitesJane Lambert
 
Cool and Crucial Online Marketing Tactics
Cool and Crucial Online Marketing TacticsCool and Crucial Online Marketing Tactics
Cool and Crucial Online Marketing Tacticsatennant
 
Boston Goes Red For Women
Boston Goes Red For WomenBoston Goes Red For Women
Boston Goes Red For Womentaylormorris
 
授業外・教室外の学習を見据えた教材設計
授業外・教室外の学習を見据えた教材設計授業外・教室外の学習を見据えた教材設計
授業外・教室外の学習を見据えた教材設計Sunami Hokuto
 
Atoms, Molecules & Stoichometry (III)
Atoms, Molecules & Stoichometry (III)Atoms, Molecules & Stoichometry (III)
Atoms, Molecules & Stoichometry (III)Bernard Ng
 
Rock your library’s content with Wordpress
Rock your library’s content with WordpressRock your library’s content with Wordpress
Rock your library’s content with Wordpresschaefele
 
Building an Academic Library Website in WordPress
Building an Academic Library Website in WordPressBuilding an Academic Library Website in WordPress
Building an Academic Library Website in WordPresschaefele
 
M&CSAATCHI.GAD Snack Planning Vol.8
M&CSAATCHI.GAD Snack Planning Vol.8M&CSAATCHI.GAD Snack Planning Vol.8
M&CSAATCHI.GAD Snack Planning Vol.8Benoît Pellevoizin
 
Moving Forward: Redesigning UNC's Library Website
Moving Forward: Redesigning UNC's Library WebsiteMoving Forward: Redesigning UNC's Library Website
Moving Forward: Redesigning UNC's Library Websitechaefele
 
House sales customer_satisfaction_survey
House sales customer_satisfaction_surveyHouse sales customer_satisfaction_survey
House sales customer_satisfaction_surveyjsembiring
 
Introduction to IP
Introduction to IPIntroduction to IP
Introduction to IPJane Lambert
 
Introduction to intellectual property handlout
Introduction to intellectual property handloutIntroduction to intellectual property handlout
Introduction to intellectual property handloutJane Lambert
 
Что помогает животным выживать
Что помогает животным выживатьЧто помогает животным выживать
Что помогает животным выживатьRaikhanaM
 
3分ではじめる、お仕着せのe-Learningからの卒業
3分ではじめる、お仕着せのe-Learningからの卒業3分ではじめる、お仕着せのe-Learningからの卒業
3分ではじめる、お仕着せのe-Learningからの卒業Sunami Hokuto
 

En vedette (20)

Ego e paparazzo
Ego e paparazzoEgo e paparazzo
Ego e paparazzo
 
Hug Concepts Content Processes
Hug Concepts Content ProcessesHug Concepts Content Processes
Hug Concepts Content Processes
 
Introduction to IP: Useful Websites
Introduction to IP: Useful WebsitesIntroduction to IP: Useful Websites
Introduction to IP: Useful Websites
 
10630
1063010630
10630
 
10630
1063010630
10630
 
Cool and Crucial Online Marketing Tactics
Cool and Crucial Online Marketing TacticsCool and Crucial Online Marketing Tactics
Cool and Crucial Online Marketing Tactics
 
Boston Goes Red For Women
Boston Goes Red For WomenBoston Goes Red For Women
Boston Goes Red For Women
 
授業外・教室外の学習を見据えた教材設計
授業外・教室外の学習を見据えた教材設計授業外・教室外の学習を見据えた教材設計
授業外・教室外の学習を見据えた教材設計
 
Marriage Is Lo
Marriage Is LoMarriage Is Lo
Marriage Is Lo
 
Atoms, Molecules & Stoichometry (III)
Atoms, Molecules & Stoichometry (III)Atoms, Molecules & Stoichometry (III)
Atoms, Molecules & Stoichometry (III)
 
Rock your library’s content with Wordpress
Rock your library’s content with WordpressRock your library’s content with Wordpress
Rock your library’s content with Wordpress
 
Building an Academic Library Website in WordPress
Building an Academic Library Website in WordPressBuilding an Academic Library Website in WordPress
Building an Academic Library Website in WordPress
 
M&CSAATCHI.GAD Snack Planning Vol.8
M&CSAATCHI.GAD Snack Planning Vol.8M&CSAATCHI.GAD Snack Planning Vol.8
M&CSAATCHI.GAD Snack Planning Vol.8
 
Moving Forward: Redesigning UNC's Library Website
Moving Forward: Redesigning UNC's Library WebsiteMoving Forward: Redesigning UNC's Library Website
Moving Forward: Redesigning UNC's Library Website
 
About Open Access
About Open AccessAbout Open Access
About Open Access
 
House sales customer_satisfaction_survey
House sales customer_satisfaction_surveyHouse sales customer_satisfaction_survey
House sales customer_satisfaction_survey
 
Introduction to IP
Introduction to IPIntroduction to IP
Introduction to IP
 
Introduction to intellectual property handlout
Introduction to intellectual property handloutIntroduction to intellectual property handlout
Introduction to intellectual property handlout
 
Что помогает животным выживать
Что помогает животным выживатьЧто помогает животным выживать
Что помогает животным выживать
 
3分ではじめる、お仕着せのe-Learningからの卒業
3分ではじめる、お仕着せのe-Learningからの卒業3分ではじめる、お仕着せのe-Learningからの卒業
3分ではじめる、お仕着せのe-Learningからの卒業
 

Similaire à jQuery Namespace Pattern

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptMiao Siyu
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5Martin Kleppe
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Elements of Functional Programming in PHP
Elements of Functional Programming in PHPElements of Functional Programming in PHP
Elements of Functional Programming in PHPJarek Jakubowski
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 
JQuery plugin development fundamentals
JQuery plugin development fundamentalsJQuery plugin development fundamentals
JQuery plugin development fundamentalsBastian Feder
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginConverting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginthehoagie
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 

Similaire à jQuery Namespace Pattern (20)

6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Advance jquery-plugin
Advance jquery-pluginAdvance jquery-plugin
Advance jquery-plugin
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
Solid principles
Solid principlesSolid principles
Solid principles
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Elements of Functional Programming in PHP
Elements of Functional Programming in PHPElements of Functional Programming in PHP
Elements of Functional Programming in PHP
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
JQuery plugin development fundamentals
JQuery plugin development fundamentalsJQuery plugin development fundamentals
JQuery plugin development fundamentals
 
Txjs
TxjsTxjs
Txjs
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginConverting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 

Dernier

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Dernier (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

jQuery Namespace Pattern

  • 1. namespace design pattern for jQuery Diego Fleury - June 2010 http://www.diegofleury.com.br http://twitter.com/diegofleury
  • 2. what we know design pattern default to write a selector based plugin jQuery.fn.myPlugin = function() { return this.each(function() { // Do something with each element }); };
  • 3. problems • Name conflict • Big plugins need other means to organize • Communication and data share between smaller parts is harder
  • 4. name conflict validate, valid, removeAttrs, form, element, resetForm, showErrors, required, remote, minlength, maxlength, email, url, date, number Generic names can cause headaches, change of plugins and desist
  • 5. plugins grandes • Bigger plugins must be sliced into parts • Alternatively as in jQuery UI $(“foo”).bar(“myAction”, “myArgument”); • Event-driven programming $(“foo”).trigger(“myAction”, [“myArgument”]);
  • 6. communicaty of parts • Contexts too permissive (globals) • Exposure (no encapsulation) • Over-parametrization
  • 7. current options • Continue as • Use existing alternatives • Namespace plugins
  • 8. namespace plugins • Expensive price to be paid • Experimental solutions • Far from natural
  • 9. Object Augmentation • Simple var foo = {}; • Flexible 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. Stopping the namespace chain $.fn.MyPlugin = function() { this.firstMethod = function() { return this.each(function() { "This method persists the namespaced chain"; }); }; this.secondMethod = function() { This serves to specific return $(this.each(function() { cases where we want to "This method persists the namespaced chain"; force the use of the })); namespace to each }; invocation 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. optimizing (function() { $.fn.MyPlugin = function() { this.firstMethod = parts.firstMethod; this.secondMethod = parts.secondMethod; return this; // Returns the jQuery's modified object }; Now, we only reference for functions already built var parts = { by the JavaScript firstMethod: function() { interpreter to execute return this.each(function() { the outer anonymous "This method persists the namespaced chain"; function }); }, secondMethod: function() { return $(this.each(function() { "This method persists the namespaced chain"; })); } }; })();
  • 14. global options (function() { var parts, globalOptions = {foo: “default”}; This can be very useful $.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. many methods (function() { var parts, globalOptions = {foo: “default”}; I recommend doing this $.fn.MyPlugin = function(globalConfig) { only when there are $.extend(globalOptions, globalConfig); many methods. This operation is expensive. $.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. Advantages • Organization • Simple to employ • Natural • Global parameterization “This is nice - it's a simple pattern to employ, for sure.” - John Resig

Notes de l'éditeur