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

Globally and Per-Call Overridable Options (Best Options Pattern)

For our next pattern, we’ll look at an optimal approach to configuring options and defaults for a plug-in. The way most of us are probably familiar with defining plug-in options is to pass through an object literal of defaults to $.extend(), as demonstrated in our basic plug-in boilerplate.

If, however, we’re working with a plug-in with many customizable options that we would like users to be able to override either globally or on a per-call level, then we can structure things a little more optimally.

Instead, by referring to an options object defined within the plug-in namespace explicitly (for example, $fn.pluginName.options) and merging this with any options passed through to the plug-in when it is initially invoked, users have the option of either passing options through during plug-in initialization or overriding options outside of the plug-in (as demonstrated here).

/*!
 * jQuery "best options" plugin boilerplate
 * Author: @cowboy
 * Further changes: @addyosmani
 * Licensed under the MIT license
 */


;(function ( $, window, document, undefined ) {

    $.fn.pluginName = function ( options ) {

        // Here's a best practice for overriding "defaults"
        // with specified options. Note how, rather than a 
        // regular defaults object being passed as the second
        // parameter, we instead refer to $.fn.pluginName.options 
        // explicitly, merging it with the options passed directly 
        // to the plug-in. This allows us to override options ...
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