SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Converting Your JS
     Library
    To a jQuery Plugin
Benefits of a jQuery plugin
● jQuery plugins encourage a certain
  structure, similar to a framework
● Plugins allow passing of options with
  sensible defaults
● Allows for code reuse on multiple DOM
  elements
● You probably aren't writing vanilla JS
  anyway, so leverage jQuery's plugin system
What Makes a Good Candidate?
● Code that needs to instantiate and keep
  internal variables
● Code that is repeated on multiple DOM
  elements across your application
● Code that is only operating on a particular
  DOM location and needs to be scoped
Let's Begin
Existing JS Lib
MyProject.MyLib = {
  init: function() {
    $('.popup a').live('click', function() {
      console.log('hello world');
    });
  }
}

$(function() {
  MyProject.MyLib.init();
});
A Few Problems...
● All functions are public - hard for the next
  person to know what functions are meant to
  be called, and often naming conventions are
  used to denote private functions (e.g. an
  underscore prefix)
● The selector is hard coded - reuse is limited
  to exactly matching selectors
● No options framework - options will probably
  be hacked in by passing data attribute
  values, etc
Not Convinced Yet?




Just Kidding, I have Solutions
And Their Solutions...
● Make private functions private, and public
  functions public. This establishes your API
● Move the selector outside of your library
● Pass options when you call your library
// You need an anonymous function to wrap around your function to avoid
conflict
(function($){
   // Attach this new method to jQuery
   $.fn.extend({
       // This is where you write your plugin's name
       pluginname: function() {
          // Iterate over the current set of matched elements
          return this.each(function() {
              // code to be inserted here
          });
       }
   });

// pass jQuery to the function,
// So that we will able to use any valid Javascript variable name
/ /to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )
})(jQuery);
Object Literal to Function
...                               ...
  init: function() {              function init(container,
    $('.popup a').live('click',   options) {
function() {                        $('a', container).bind('click',
     console.log('hello           function() {
world');                              console.log('hello world');
    });                             });
  }                               }
...                               ...
Initialization of JS Lib
$(function() {       ...
  MyProject.MyLib.   this.each(function() {
init()                 init(this, options);
});                  });
                     ...

                     $('popup').myLib();
Private Functions
init, and everything      init is not public in
else in your object       jQuery, and can only
literal is public         be called internally

MyProject.MyLib.init();   var a=$('.popup').
                          myLib();
                          a.init();
                          # no method 'init'
Public Functions
init, and everything      function init() {
else in your object          console.log('hello world');
literal is public         }
                          this.each(function() {
                          // code to be inserted here
MyProject.MyLib.init();   });
                          return { init: init };



                          var a = $('.foo').myLib();
                          a.init();
Code Reuse on Different Selectors
Reuse is limited to       Selectors are
parts of the DOM          specified at
where the selectors       initialization
exactly match
                          $('.here').myLib();
MyProject.MyLib.init();   $('.there').myLib();
Passing Options in Your Lib
Options can be          Options can be
passed to init(), but   passed in at
would be globally set   initialization:

MyProject.MyLib.init    $('.popup').myLib({
({foo: 'bar'});         foo: 'bar' });
MyProject.MyLib.init    $('.other').myLib({
({foo: 'baz'});         foo: 'baz' });
And the Final Plugin
(function($){
   $.fn.extend({
       myLib: function(options) {
         function init(container, options) {
           $('a', container).bind('click', function() {
             console.log(options.message);
           });
         }
         var options = $.extend(defaults, options);
         return this.each(function() {
             init(this, options);
         });
       }
   });
})(jQuery);

$('.popup').myLib({message: 'hello world'});
The Wrap Up
● In under 20 lines we have a fully functional
  jQuery plugin
● We have options support
● We have public / private functions
● We can reuse this on different selectors
Final Thoughts
● jQuery is for manipulating the DOM. I
  wouldn't recommend making jQuery plugins
  for Node.js libraries, etc
● Get familiar with Javascript outside of the
  DOM. He can be opinionated, but I have to
  recommend Javascript: The Good Parts by
  Douglas Crockford
● Do stuff in Node.js. The exposure to
  Javascript in a different context is very
  helpful
Resources
● This is a great jQuery tutorial: http://www.
    queness.com/post/112/a-really-simple-jquery-plugin-
    tutorial
●   The official docs: http://docs.jquery.
    com/Plugins/Authoring
●   Node.js: http://nodejs.org/
●   Javascript: The Good Parts: http://amzn.
    to/Lpn7Jx

Mais conteúdo relacionado

Mais procurados

Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryWingify Engineering
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusTakeshi AKIMA
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
How to work with legacy code
How to work with legacy codeHow to work with legacy code
How to work with legacy codeMichał Kruczek
 
How to work with legacy code PHPers Rzeszow #2
How to work with legacy code PHPers Rzeszow #2How to work with legacy code PHPers Rzeszow #2
How to work with legacy code PHPers Rzeszow #2Michał Kruczek
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5mennovanslooten
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinMarco Vasapollo
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
 

Mais procurados (20)

Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQuery
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeus
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
How to work with legacy code
How to work with legacy codeHow to work with legacy code
How to work with legacy code
 
How to work with legacy code PHPers Rzeszow #2
How to work with legacy code PHPers Rzeszow #2How to work with legacy code PHPers Rzeszow #2
How to work with legacy code PHPers Rzeszow #2
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 

Semelhante a Converting your JS library to a jQuery plugin

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin developmentFaruk Hossen
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 

Semelhante a Converting your JS library to a jQuery plugin (20)

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Advance jquery-plugin
Advance jquery-pluginAdvance jquery-plugin
Advance jquery-plugin
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin development
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery
jQueryjQuery
jQuery
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 

Mais de thehoagie

Pair programming
Pair programmingPair programming
Pair programmingthehoagie
 
Docker presentation
Docker presentationDocker presentation
Docker presentationthehoagie
 
Database 101
Database 101Database 101
Database 101thehoagie
 
Git Pro Tips
Git Pro TipsGit Pro Tips
Git Pro Tipsthehoagie
 
Null object pattern
Null object patternNull object pattern
Null object patternthehoagie
 
Big tables and you - Keeping DDL operatations fast
Big tables and you - Keeping DDL operatations fastBig tables and you - Keeping DDL operatations fast
Big tables and you - Keeping DDL operatations fastthehoagie
 
Angular.js - An introduction for the unitiated
Angular.js - An introduction for the unitiatedAngular.js - An introduction for the unitiated
Angular.js - An introduction for the unitiatedthehoagie
 
Regular expression presentation for the HUB
Regular expression presentation for the HUBRegular expression presentation for the HUB
Regular expression presentation for the HUBthehoagie
 
Active records before_type_cast
Active records before_type_castActive records before_type_cast
Active records before_type_castthehoagie
 

Mais de thehoagie (11)

Pair programming
Pair programmingPair programming
Pair programming
 
Docker presentation
Docker presentationDocker presentation
Docker presentation
 
Database 101
Database 101Database 101
Database 101
 
Testing
TestingTesting
Testing
 
Hubot
HubotHubot
Hubot
 
Git Pro Tips
Git Pro TipsGit Pro Tips
Git Pro Tips
 
Null object pattern
Null object patternNull object pattern
Null object pattern
 
Big tables and you - Keeping DDL operatations fast
Big tables and you - Keeping DDL operatations fastBig tables and you - Keeping DDL operatations fast
Big tables and you - Keeping DDL operatations fast
 
Angular.js - An introduction for the unitiated
Angular.js - An introduction for the unitiatedAngular.js - An introduction for the unitiated
Angular.js - An introduction for the unitiated
 
Regular expression presentation for the HUB
Regular expression presentation for the HUBRegular expression presentation for the HUB
Regular expression presentation for the HUB
 
Active records before_type_cast
Active records before_type_castActive records before_type_cast
Active records before_type_cast
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Converting your JS library to a jQuery plugin

  • 1. Converting Your JS Library To a jQuery Plugin
  • 2. Benefits of a jQuery plugin ● jQuery plugins encourage a certain structure, similar to a framework ● Plugins allow passing of options with sensible defaults ● Allows for code reuse on multiple DOM elements ● You probably aren't writing vanilla JS anyway, so leverage jQuery's plugin system
  • 3. What Makes a Good Candidate? ● Code that needs to instantiate and keep internal variables ● Code that is repeated on multiple DOM elements across your application ● Code that is only operating on a particular DOM location and needs to be scoped
  • 5. Existing JS Lib MyProject.MyLib = { init: function() { $('.popup a').live('click', function() { console.log('hello world'); }); } } $(function() { MyProject.MyLib.init(); });
  • 6. A Few Problems... ● All functions are public - hard for the next person to know what functions are meant to be called, and often naming conventions are used to denote private functions (e.g. an underscore prefix) ● The selector is hard coded - reuse is limited to exactly matching selectors ● No options framework - options will probably be hacked in by passing data attribute values, etc
  • 7. Not Convinced Yet? Just Kidding, I have Solutions
  • 8. And Their Solutions... ● Make private functions private, and public functions public. This establishes your API ● Move the selector outside of your library ● Pass options when you call your library
  • 9. // You need an anonymous function to wrap around your function to avoid conflict (function($){ // Attach this new method to jQuery $.fn.extend({ // This is where you write your plugin's name pluginname: function() { // Iterate over the current set of matched elements return this.each(function() { // code to be inserted here }); } }); // pass jQuery to the function, // So that we will able to use any valid Javascript variable name / /to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) ) })(jQuery);
  • 10. Object Literal to Function ... ... init: function() { function init(container, $('.popup a').live('click', options) { function() { $('a', container).bind('click', console.log('hello function() { world'); console.log('hello world'); }); }); } } ... ...
  • 11. Initialization of JS Lib $(function() { ... MyProject.MyLib. this.each(function() { init() init(this, options); }); }); ... $('popup').myLib();
  • 12. Private Functions init, and everything init is not public in else in your object jQuery, and can only literal is public be called internally MyProject.MyLib.init(); var a=$('.popup'). myLib(); a.init(); # no method 'init'
  • 13. Public Functions init, and everything function init() { else in your object console.log('hello world'); literal is public } this.each(function() { // code to be inserted here MyProject.MyLib.init(); }); return { init: init }; var a = $('.foo').myLib(); a.init();
  • 14. Code Reuse on Different Selectors Reuse is limited to Selectors are parts of the DOM specified at where the selectors initialization exactly match $('.here').myLib(); MyProject.MyLib.init(); $('.there').myLib();
  • 15. Passing Options in Your Lib Options can be Options can be passed to init(), but passed in at would be globally set initialization: MyProject.MyLib.init $('.popup').myLib({ ({foo: 'bar'}); foo: 'bar' }); MyProject.MyLib.init $('.other').myLib({ ({foo: 'baz'}); foo: 'baz' });
  • 16. And the Final Plugin
  • 17. (function($){ $.fn.extend({ myLib: function(options) { function init(container, options) { $('a', container).bind('click', function() { console.log(options.message); }); } var options = $.extend(defaults, options); return this.each(function() { init(this, options); }); } }); })(jQuery); $('.popup').myLib({message: 'hello world'});
  • 18. The Wrap Up ● In under 20 lines we have a fully functional jQuery plugin ● We have options support ● We have public / private functions ● We can reuse this on different selectors
  • 19. Final Thoughts ● jQuery is for manipulating the DOM. I wouldn't recommend making jQuery plugins for Node.js libraries, etc ● Get familiar with Javascript outside of the DOM. He can be opinionated, but I have to recommend Javascript: The Good Parts by Douglas Crockford ● Do stuff in Node.js. The exposure to Javascript in a different context is very helpful
  • 20. Resources ● This is a great jQuery tutorial: http://www. queness.com/post/112/a-really-simple-jquery-plugin- tutorial ● The official docs: http://docs.jquery. com/Plugins/Authoring ● Node.js: http://nodejs.org/ ● Javascript: The Good Parts: http://amzn. to/Lpn7Jx