Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced content levelIntermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

A Lightweight Start Pattern

Let’s begin our deeper look at plug-in patterns with something basic that follows best practices (including those in the jQuery plug-in authoring guide). This pattern is ideal for developers who are either new to plug-in development or who just want to achieve something simple (such as a utility plug-in). A Lightweight start uses the following:

  • Common best practices such as a semicolon placed before the function’s invocation (we’ll go through why in the comments below).

  • window, document, and undefined passed in as arguments.

  • A basic defaults object.

  • A simple plug-in constructor for logic related to the initial creation and the assignment of the element to work with.

  • Extending the options with defaults.

  • A lightweight wrapper around the constructor, which helps to avoid issues such as multiple instantiations.

  • Adherence to the jQuery core style guidelines for maximized readability.

/*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */


// the semi-colon before the function invocation is a safety 
// net against concatenated scripts and/or other plug-ins 
// that are not closed properly.
;(function ( $, window, document, undefined ) {
    
    // undefined is used here as the undefined global 
    // variable in ECMAScript 3 and is mutable (i.e. it can 
    // be changed by someone else). undefined isn't really 
    // being passed in so we can ensure that its value is 
    // truly undefined. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page