Slide 1

Slide 1 text

Writing Maintainable & Reusable JavaScript by Natalie MacLees @nataliemac | nataliemac.com

Slide 2

Slide 2 text

Why is maintainability important?

Slide 3

Slide 3 text

JavaScript mistakes you’re probably making

Slide 4

Slide 4 text

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 } ... });

Slide 5

Slide 5 text

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();

Slide 6

Slide 6 text

Inconsistently using style conventions var newText = ‘Hello World!”; ! var some_other_text = “Hi there!”; ! var yetSomeMoreText = “Bonjour!”;

Slide 7

Slide 7 text

Not maintaining separation Click me! $(‘a’).css({
 ‘color’: ‘green’;
 ‘fontSize’: ‘2em’;
 }); var lightbox = $(‘
’);

Slide 8

Slide 8 text

The wild, wild West of JavaScript

Slide 9

Slide 9 text

Understandable Future-proof Readable Modifiable Extensible Testable What does maintainable & reusable mean?

Slide 10

Slide 10 text

Writing better JavaScript 1 2 3 4 5 Style conventions Programming practices Modular pattern jQuery plugins Automation

Slide 11

Slide 11 text

1 Style conventions

Slide 12

Slide 12 text

Spaces vs tabs

Slide 13

Slide 13 text

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’);

Slide 14

Slide 14 text

Keep lines as short as possible $(‘ul’) .slideDown() .find(‘li’) .addClass(‘open’) .prepend(‘+’) .end() .addClass(‘parent-open’);

Slide 15

Slide 15 text

Use comments like salt in soup

Slide 16

Slide 16 text

Use logical names for functions and variables (even if they’re long)

Slide 17

Slide 17 text

Use camelCase

Slide 18

Slide 18 text

camelCase & abbreviations and acronynms getElementById() innerHTML() XMLHttpRequest()

Slide 19

Slide 19 text

2 Programming practices

Slide 20

Slide 20 text

Keep layers separate CSS: .highlight {
 color: green;
 fontSize: 2em;
 } JavaScript: $(‘a’).addClass(‘highlight’);

Slide 21

Slide 21 text

Keep layers separate

{{title}}

{{body}}

Slide 22

Slide 22 text

Don’t modify objects you don’t own

Slide 23

Slide 23 text

Event handlers should only handle events $(‘.next’).on(‘click’, function(){ var slider = $(‘#slider’), currentSlide = slider.find(‘.current’), nextSlide = currentSlide.next(); currentSlide.fadeOut(); nextSlide.fadeIn(); });

Slide 24

Slide 24 text

Event handlers should only handle events $(‘.next’).on(‘click’, function(){ nextSlide(); }); ! function nextSlide() { // code to advance to next slide here }

Slide 25

Slide 25 text

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!”; } }

Slide 26

Slide 26 text

Separate config data var config = { url: ‘https://api.twitter.com/...', tweetsToShow: 5, tweetContainer: $(‘#tweets’) };

Slide 27

Slide 27 text

Avoid global functions & variables

Slide 28

Slide 28 text

3 Modular Pattern

Slide 29

Slide 29 text

Object literal var projectName = { config: { numberofTweets: 5, url: ‘http://api.twitter.com...', container: $(‘tweets’) }, init: function() { // get everything going }, ...

Slide 30

Slide 30 text

Object literal jQuery(function(){ projectName.init(); }; ! var projectName = { config: { ... }, init: function() { // initialize the project } }

Slide 31

Slide 31 text

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(); });

Slide 32

Slide 32 text

4 jQuery plugins

Slide 33

Slide 33 text

Use an immediately invoked function expression ;(function($){ $.fn.venturaSlider = function(options){ // Plugin code goes here } })(jQuery);

Slide 34

Slide 34 text

window, document, undefined ;(function($, window, document, undefined){ $.fn.venturaSlider = function(options){ // Plugin code goes here } })(jQuery, window, document);

Slide 35

Slide 35 text

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);

Slide 36

Slide 36 text

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);

Slide 37

Slide 37 text

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);

Slide 38

Slide 38 text

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);

Slide 39

Slide 39 text

5 Automation

Slide 40

Slide 40 text

Break JavaScript into multiple files

Slide 41

Slide 41 text

Minify, compress, & deploy

Slide 42

Slide 42 text

Maintainable & reusable code matters 1 2 3 4 5 Style conventions Programming practices Modular pattern jQuery plugins Automation

Slide 43

Slide 43 text

–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.”

Slide 44

Slide 44 text

–Chris Eppstein, creator of Compass “Be kind to your future self.”

Slide 45

Slide 45 text

Thank you! Questions?