Writing Maintainable and Reusable JavaScript

Writing Maintainable and Reusable JavaScript

It’s really easy for JavaScript files in a theme or plugin to quickly become a big, hairy mess. So let’s take a look at how to structure JavaScript code in a way that makes it easier to read and understand, easier to maintain, and prevents pollution of the global namespace. We’ll cover modular JavaScript structure and writing plugins.

9c9bcdbab2f098f69b3adadde6ee2936?s=128

Natalie MacLees

November 08, 2014
Tweet

Transcript

  1. 4.

    Writing all your code inside document ready jQuery(document).ready(function($){ function slideShow()

    { // some code that makes a slideshow } ! function newsTicker() { // some code that makes a news ticker } ... });
  2. 5.

    Using global scope for all your variables and functions var

    newText = ‘Hello World’; ! function addText() { var container = $(‘textContainer’); container.text(newText); } ! var height = window.height();
  3. 6.

    Inconsistently using style conventions var newText = ‘Hello World!”; !

    var some_other_text = “Hi there!”; ! var yetSomeMoreText = “Bonjour!”;
  4. 7.

    Not maintaining separation <a href=“#” onclick=“doSomething();”>Click me!</a> $(‘a’).css({
 ‘color’: ‘green’;


    ‘fontSize’: ‘2em’;
 }); var lightbox = $(‘<div class=“overlay”></div><div class=“lightbox”><img src=“”/><div class=“lightbox- title”></div></div>’);
  5. 10.

    Writing better JavaScript 1 2 3 4 5 Style conventions

    Programming practices Modular pattern jQuery plugins Automation
  6. 13.

    Keep lines as short as possible if ( tod ==

    ‘morning’ ) { $(‘.greeting’).text(‘Good morning’) } else { $(‘.greeting’).text(‘Good afternoon!’) } ! $ (‘ul’).slideDown().find(‘li’).addClass(‘open’).prepe nd(‘+’).end().addClass(‘parent-open’);
  7. 20.

    Keep layers separate CSS: .highlight {
 color: green;
 fontSize: 2em;


    } JavaScript: $(‘a’).addClass(‘highlight’);
  8. 23.

    Event handlers should only handle events $(‘.next’).on(‘click’, function(){ var slider

    = $(‘#slider’), currentSlide = slider.find(‘.current’), nextSlide = currentSlide.next(); currentSlide.fadeOut(); nextSlide.fadeIn(); });
  9. 24.

    Event handlers should only handle events $(‘.next’).on(‘click’, function(){ nextSlide(); });

    ! function nextSlide() { // code to advance to next slide here }
  10. 25.

    Throw your own errors Twitlicious.addTweets = function(container) { if (

    container instanceof jQuery) { container.append(Twitlicious.tweets); } else { throw new Error “addTweets: This is not a jQuery object!”; } }
  11. 29.

    Object literal var projectName = { config: { numberofTweets: 5,

    url: ‘http://api.twitter.com...', container: $(‘tweets’) }, init: function() { // get everything going }, ...
  12. 30.

    Object literal jQuery(function(){ projectName.init(); }; ! var projectName = {

    config: { ... }, init: function() { // initialize the project } }
  13. 31.

    Immediately invoked function expression (IIFE) ;(function ($, projectName, undefined) {

    var linkClick = function() { // private $(‘a’).on(‘click’, function(){ //do something when links are clicked }); }; projectName.init = function() { // public linkClick(); }; }(jQuery, window.projectName = window.projectName || {})); ! jQuery(function(){ projectName.init(); });
  14. 35.

    Iterate over each item in the collection ;(function($, window, document,

    undefined){ $.fn.venturaSlider = function(options){ this.each(function(){ // Do something to each item }); } })(jQuery, window, document);
  15. 36.

    Use .data() to store instance details ;(function($, window, document, undefined){

    $.fn.venturaSlider = function(options){ this.each(function(){ var $this = $(this); $this.data(‘current’, 1); }); } })(jQuery, window, document);
  16. 37.

    Allow customization & use extend() ;(function($, window, document, undefined){ $.fn.venturaSlider

    = function(options){ var opts = $.extend( {}, $.fn.venturaSlider.defaults, options); ... } $.fn.venturaSlider.defaults = { // Define default settings }; })(jQuery, window, document);
  17. 38.

    Return the jQuery object for chaining ;(function($, window, document, undefined){

    $.fn.venturaSlider = function(options){ var opts = $.extend( {}, $.fn.venturaSlider.defaults, options); ... return this; } $.fn.venturaSlider.defaults = {}; })(jQuery, window, document);
  18. 42.

    Maintainable & reusable code matters 1 2 3 4 5

    Style conventions Programming practices Modular pattern jQuery plugins Automation
  19. 43.

    –Rick Osborne, creator of TorrentSpy “Always code as if the

    person who ends up maintaining your code is a violent psychopath who knows where you live.”