SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Ähnlich wie Converting your JS library to a jQuery plugin

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
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
erockendude
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 

Ähnlich wie 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
 

Mehr von thehoagie

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

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.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