Chapter 6. Customizing Your Plugins

So far, we have built the MyPhoto demo page leveraging all that Bootstrap has to offer, customizing Bootstrap's themes and components, and using jQuery plugins along the way. In this chapter, we will be delving deep into Bootstrap's jQuery plugins with extensive customization via JavaScript and CSS.

We will take some of the plugins we have introduced into MyPhoto, take a look under the hood, and, step by step, we will customize them to meet the needs of our page. Plugins will be examined and extended throughout this chapter in an effort to not only make our page better, but to also build our knowledge of how jQuery plugins are built and behave within Bootstrap's ecosystem.

When we are comfortable with customizing Bootstrap's jQuery plugins, we will create a fully customized jQuery plugin of our own for MyPhoto.

Summarizing all of this, in this chapter we will globally do the following:

  • Learn about the anatomy of a Bootstrap jQuery plugin
  • Learn how to extensively customize the behavior and features of Bootstrap's jQuery plugins via JavaScript
  • Learn how to extensively customize the styling of Bootstrap's jQuery plugins via CSS
  • Learn how to create a custom Bootstrap jQuery plugin from scratch

Anatomy of a plugin

Bootstrap jQuery plugins all follow the same convention in how they are constructed. At the top level, a plugin is generally split across two files, a JavaScript file and a Sass file. For example, the Alert component is made up of bootstrap/js/alert.js and bootstrap/scss/_alert.scss. These files are compiled and concatenated as part of Bootstrap's distributable JavaScript and CSS files. Let us look at these two files in isolation to learn about the anatomy of a plugin.

JavaScript

Open up any JavaScript file in bootstrap/js/src, and you will see that they all follow the same pattern: an initial setup, a class definition, data API implementation, and jQuery extension. Let's take a detailed look at alert.js.

Setup

The alert.js file, written in ECMAScript 2015 syntax (also known as ES6, the latest (at the time of writing) standardized specification of JavaScript), first imports a utilities module:

    import Util from './util'

A constant is then created, named Alert, which is assigned the result of an Immediately Invoked Function Expression (IIFE):

    const Alert = (($) => {
    ...
    })(jQuery)

A jQuery object is being passed into a function for execution, the result of which will be assigned to the immutable Alert constant.

Within the function itself, a number of constants are also declared for use throughout the rest of the code. Declaring immutables at the beginning of the file is generally seen as best practice. Observe the following code:

    const NAME                = 'alert'
    const VERSION             = '4.0.0-alpha'
    const DATA_KEY            = 'bs.alert'
    const EVENT_KEY           = '.${DATA_KEY}'
    const DATA_API_KEY        = '.data-api'
    const JQUERY_NO_CONFLICT  = $.fn[NAME]
    const TRANSITION_DURATION = 150
    
    const Selector = {
      DISMISS : '[data-dismiss="alert"]'
    }
    const Event = {
      CLOSE : 'close${EVENT_KEY}',
      CLOSED : 'closed${EVENT_KEY}',
      CLICK_DATA_API : 'click${EVENT_KEY}${DATA_API_KEY}'
    }
    
    const ClassName = {
      ALERT : 'alert',
      FADE : 'fade',
      IN : 'in'
    }

The NAME property is the name of the plugin, and VERSION defines the version of the plugin, which generally correlates to the version of Bootstrap. DATA_KEY, EVENT_KEY, and DATA_API_KEY relate to the data attributes that the plugin hooks into, while the rest are coherent, more readable, aliases for the various values used throughout the plugin code. Following that is the class definition.

Note

Immediately Invoked Function Expression

An Immediately Invoked Function Expression (IIFE or iffy) is a function which is executed as soon as it has been declared, and is known as a self-executing function in other languages. A function is declared as an IIFE by either wrapping the function in parentheses or including a preceding unary operator, and including a trailing pair of parentheses. Examples:

(function(args){ })(args)
!function(args){ }(args)

Class definition

Near the top of any of the plugin JS files, you will see a comment declaring the beginning of the class definition for that particular plugin. In the case of alerts, it is:

    /**
    * -------------------------------------------------------------------
    -----    
    * Class Definition
    * -------------------------------------------------------------------
    -----
    */

The class definition is simply the constructor of the base object, in this case, the Alert object:

    class Alert {
        constructor(element) {
            this._element = element
        }
        ...
    }

The convention with plugins is to use Prototypal inheritance. The Alert base object is the object all other Alert type objects should extend and inherit from. Within the class definition, we have the public and private functions of the Alert class. Let's take a look at the public close function:

    close(element) {
        element = element || this._element
        let rootElement = this._getRootElement(element)
        let customEvent = this._triggerCloseEvent(rootElement)
        if (customEvent.isDefaultPrevented()) {
          return
        }
        
        this._removeElement(rootElement)
    }

The close function takes an element as an argument, which is the reference to the DOM element the close function is to act upon. The close function uses the private function _getRootElement to retrieve the specific DOM element, and _triggerCloseEvent to reference the specific event to be processed. Finally, close calls _removeElement. Let's take a look at these private functions:

    _getRootElement(element) {
        let selector = Util.getSelectorFromElement(element)
        let parent   = false
        
        if (selector) {
            parent = $(selector)[0]
        }
        
        if (!parent) {
            parent = $(element).closest(`.${ClassName.ALERT}`)[0]
        }
        return parent
    }

The _getRootElement tries to find the parent element of the DOM element passed to the calling function, in this case, close. If a parent does not exist, _getRootElement returns the closest element with the class name defined by ClassName.ALERT in the plugin's initial setup. This in our case is Alert. Observe the following code:

    _triggerCloseEvent(element) {
        let closeEvent = $.Event(Event.CLOSE)
        $(element).trigger(closeEvent)
        return closeEvent
    }

The _triggerCloseEvent also takes an element as an argument and triggers the event referenced in the plugin's initial setup by Event.CLOSE:

    _removeElement(element) {
        $(element).removeClass(ClassName.IN)
        if (!Util.supportsTransitionEnd() ||
            !$(element).hasClass(ClassName.FADE)) {
          this._destroyElement(element)
          return
        }
        $(element)
            .one(Util.TRANSITION_END, $.proxy(this._destroyElement,
            this, element))
            .emulateTransitionEnd(TRANSITION_DURATION)
    }

The _removeElement then carries out the removal of the rootElement safely and in accordance with the configuration in the element itself, or as defined in the plugin's initial setup, for example, TRANSITION_DURATION.

All core behaviors and functions of the plugin should be defined in the same manner as the close function. The class definition represents the plugin's essence.

After the public and private functions come the static functions. These functions, which are also private, are similar to what would be described as the plugin definition in Bootstrap 3. Observe the following code:

    static _jQueryInterface(config) {
        return this.each(function () {
            let $element = $(this)
            let data = $element.data(DATA_KEY)
            if (!data) {
                data = new Alert(this)
                $element.data(DATA_KEY, data)
            }
            if (config === 'close') {
                data[config](this)
            }
        })
    }
    static _handleDismiss(alertInstance) {
        return function (event) {
            if (event) {
                event.preventDefault()
            }
            alertInstance.close(this)
        }
    }

The _jQueryInterface is quite simple. First, it loops through an array of DOM elements. This array is represented here by the this object. It creates a jQuery wrapper around each element and then creates the Alert instance associated with this element, if it doesn't already exist. _jQueryInterface also takes in a config argument. As you can see, the only value of config that _jQueryInterface is concerned with is 'close'. If config equals 'close', then the Alert will be closed automatically.

_handleDismiss simply allows for a specific instance of Alert to be programmatically closed.

Following the class definition, we have the data API implementation.

Data API implementation

The role of the data API implementation is to create JavaScript hooks on the DOM, listening for actions on elements with a specific data attribute. In alert.js, there is only one hook:

    $(document).on(
        Event.CLICK_DATA_API,
        Selector.DISMISS,
        Alert._handleDismiss(new Alert())
    )
    $(document).on('click.bs.alert.data-api', dismiss,
    Alert.prototype.close)

The hook is an on-click listener on any element that matches the dismiss selector.

When a click is registered, the close function of Alert is invoked. The dismiss selector here has actually been defined at the beginning of the file, in the plugin setup:

    const Selector = {
        DISMISS : '[data-dismiss="alert"]'
    }

Therefore, an element with the attribute data-dismiss="alert" will be hooked in, to listen for clicks. The click event reference is also defined in the setup:

    const Event = {
        CLOSE          : 'close${EVENT_KEY}',
        CLOSED         : 'closed${EVENT_KEY}',
        CLICK_DATA_API : 'click${EVENT_KEY}${DATA_API_KEY}'
    }

EVENT_KEY and DATA_API_KEY, if you remember, are also defined here:

    const DATA_KEY             = 'bs.alert'
    const EVENT_KEY          = '.${DATA_KEY}'
    const DATA_API_KEY     = '.data-api'

We could actually rewrite the API definition to read as follows:

    $(document).on('click.bs.alert.data-api', '[data-dismiss="alert"]', 
    Alert._handleDismiss(new Alert()))

The last piece of the puzzle is the jQuery section, which is a new feature in Bootstrap 4. It is a combination of Bootstrap 3's plugin definition and a conflict prevention pattern.

jQuery

The jQuery section is responsible for adding the plugin to the global jQuery object so that it is made available anywhere in an application where jQuery is available. Let's take a look at the code:

    $.fn[NAME]             = Alert._jQueryInterface
    $.fn[NAME].Constructor = Alert
    $.fn[NAME].noConflict  = function () {
        $.fn[NAME] = JQUERY_NO_CONFLICT
        return Alert._jQueryInterface
    }

The first two assignments extend jQuery's prototype with the plugin function. As Alert is created within a closure, the constructor itself is actually private. Creating the Constructor property on $.fn.alert allows it to be accessible publicly.

Then, a property of $.fn.alert called noConflict is assigned the value of Alert._jQueryInterface. The noConflict property comes into use when trying to integrate Bootstrap with other frameworks to resolve issues with two jQuery objects with the same name. If in some framework the Bootstrap Alert got overridden, we could use noConflict to access the Bootstrap Alert and assign it to a new variable:

    $.fn.bsAlert = $.fn.alert.noConflict()

$.fn.alert is the framework version of Alert, but we have transferred the Bootstrap Alert to $.fn.bsAlert.

All plugins tend to follow the pattern of initial setup, class definition, data API implementation, and jQuery extension. To accompany the JavaScript, a plugin also has its own specific Sass style sheet.

Sass

Sass files for plugins aren't as formulaic as the corresponding JavaScript. In general, JavaScript hooks into classes and attributes to carry out a generally simple functionality. In a lot of cases, much of the functionality is actually controlled by the style sheet; the JavaScript simply adds and removes classes or elements under certain conditions. The heavy lifting is generally carried out by the Sass, so it is understandable that the Sass itself may not fit into a uniform pattern.

Let's take a look at scss/_alert.scss. The _alert.scss opens up with a base style definition. Most, but not all, plugins will include a base definition (usually preceded by a base style or base class comment). Defining the base styles of a plugin at the beginning of the Sass file is best practice for maintainability and helps anyone who might want to extend the plugin to understand it.

Following the base styles, the styles associated with, or responsible for, the functionality of the plugin are defined. In the case of alerts, the dismissible alert styles are defined. The only piece of functionality an alert has, besides being rendered on the page, is to be dismissed. This is where Alerts defines what should happen when the close class is applied to an Alerts element.

The Sass will also generally include an alternate style definition. The alternate styles generally align with Bootstrap's contextual classes, which we explored in Chapter 2, Making a Style Statement. Observe the following code:

    // Alternate styles
    //
    // Generate contextual modifier classes for colorizing the alert.
    .alert-success {
        @include alert-variant($alert-success-bg, $alert-success-border,
        $alert-success-text);
    }
    .alert-info {
        @include alert-variant($alert-info-bg, $alert-info-border, 
        $alert-info-text);
    }
    .alert-warning {
        @include alert-variant($alert-warning-bg, $alert-warning-border,
        $alert-warning-text);
    }
    .alert-danger {
        @include alert-variant($alert-danger-bg, $alert-danger-border, 
        $alert-danger-text);
    }

As you can see, alert provides styles to correspond with the success, info, warning, and danger contexts. The variables used in the rules, such as $alert-danger-bg, are declared in _variables.scss. Declaring variables in a _variables.scss file is best practice, as otherwise maintenance would be supremely difficult. For instance, open up _variables.scss and see the definition for $alert-danger-bg:

    $alert-warning-bg: $state-warning-bg !default;

The $state-warning-bg is another variable, but this variable is used for all form feedback and alert warning background variables. If we wanted to change the color that the warning context corresponds to, we would just need to change the value in one place:

    $state-warning-bg: #fcf8e3 !default;

Beyond the base styles and, to an extent, the alternate styles, there is no real template for plugging in the Sass files.

The JavaScript file and the Sass file are the two ingredients that make a plugin work. Looking at the example from Chapter 4, On Navigation, Footers, Alerts, and Content,we can see the alert plugin in action:

    <div class="alert alert-danger">
        <a href="#" class="close" data-dismiss="alert" 
        aria-label="close">&times;</a>
        <strong class="alert-heading"><i class="fa fa-
        exclamation"></i> Unsupported browser</strong>
        Internet Explorer 8 and lower are not supported by this website.
    </div>

Let's start customizing plugins.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.134