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

Patterns

jQuery plug-ins have few concrete rules, which is one of the reasons for the incredible diversity in how they are implemented across the community. At the most basic level, we can write a plug-in simply by adding a new function property to jQuery’s jQuery.fn object, as follows:

$.fn.myPluginName = function () {
    // our plugin logic
};

This is great for compactness, but the following would be a better foundation to build on:

(function( $ ){
  $.fn.myPluginName = function () {
    // our plugin logic
  };
})( jQuery );

Here, we’ve wrapped our plug-in logic in an anonymous function. To ensure that our use of the $ sign as a shorthand creates no conflicts between jQuery and other JavaScript libraries, we simply pass it to this closure, which maps it to the dollar sign. This ensures that it can’t be affected by anything outside of its scope of execution.

An alternative way to write this pattern would be to use jQuery.extend(), which enables us to define multiple functions at once and sometimes make more sense semantically:

(function( $ ){
    $.extend($.fn, {
        myplugin: function(){
            // your plugin logic
        }
    });
})( jQuery );

We have now reviewed some jQuery plug-in fundamentals, but a lot more could be done to take this further. A Lightweight Start is the first complete plug-in design pattern we’ll be exploring, and it covers some best practices that we can use for basic everyday plug-in development, taking into account common gotchas worth applying.

Note

While most of the patterns below will be explained, ...

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