SlideShare a Scribd company logo
1 of 20
Download to read 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

More Related Content

What's hot

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
 

What's hot (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
 

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

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

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

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

Recently uploaded

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Introduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxIntroduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxmprakaash5
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Memoori
 
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
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationBuild Intuit
 
Arti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfArti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfwill854175
 
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
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024BookNet Canada
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactivestartupro
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Which standard is best for your content?
Which standard is best for your content?Which standard is best for your content?
Which standard is best for your content?Rustici Software
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfROWELL MARQUINA
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...BookNet Canada
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 

Recently uploaded (20)

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Introduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxIntroduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptx
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!
 
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
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientation
 
Arti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfArti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdf
 
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...
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactive
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Which standard is best for your content?
Which standard is best for your content?Which standard is best for your content?
Which standard is best for your content?
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdf
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 

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