loading...

Bootstrap 4 – 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’s 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 jQuery and a utilities module:

import $ from 'jquery'    
import Util from './util'

A constant named Alert is then created, 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'
    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',
      SHOW : 'show'
    }

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.

Immediately Invoked Function Expression

An IIFE or iffy is a function that is executed as soon as it has been declared, and it 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. Consider these 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 this:

    /**
    * -------------------------------------------------------------------
    -----    
    * 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
        const rootElement = this._getRootElement(element)
        const 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 _getRootElement private function 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) {
        const 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, close in this case. 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) {
        const 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.SHOW)
        if (!Util.supportsTransitionEnd() ||
            !$(element).hasClass(ClassName.FADE)) {
            this._destroyElement(element)
            return
        }
        $(element).one(Util.TRANSITION_END, (event) =>                                               
            this._destroyElement(element, event))
         .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 () {
        const $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())
    )

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 data-dismiss="alert" attribute 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 can 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 can 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 a 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 define 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.

@each $color, $value in $theme-colors {
  .alert-#{$color} {
    @include alert-variant(theme-color-level($color, -10), theme-color-level($color, -9), theme-color-level($color, 6));
  }
}

The $theme-color variable is defined in _variables.scss as follows:

$theme-colors: (
     primary: $blue,
     secondary: $gray-600,
     success: $green,
     info: $cyan,
     warning: $yellow,
     danger: $red,
     light: $gray-100,
     dark: $gray-800
) !default;

Declaring variables in a _variables.scss file is best practice, as otherwise maintenance will be supremely difficult.

As you can see, alert provides styles to correspond with the success, info, warning, and danger contexts by iterating through the theme colors. Also, beyond these 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 alert-dismissible alert-myphoto 
   fixed-top">
   <a href="#" class="close" data-dismiss="alert" aria-
      label="close">&times;</a>
   <strong >Unsupported
   browser</strong>
   Internet Explorer 8 and lower are not supported by this website.
</div>

Now that we have learned a bit about the anatomy of the, we are ready to start customizing plugins.

Comments are closed.

loading...