mercredi 19 août 2020

What do you call a pattern that uses a eventBus to interact with all its components ( Slides / Dots / Arrows )

I have been playing around for a while with the code of glide.js and have been quite facinated by the design pattern used in Glide.js , that looks something like below, below is just the edited gist of the code , but i really have never seen something quite like this :-

The full code can be found HERE.

import defaults from './defaults'
import { warn } from './utils/log'
import { mount } from './core/index'
import { mergeOptions } from './utils/object'
import { toInt, isObject, isArray } from './utils/unit'

import EventsBus from './core/event/events-bus'

export default class Glide {
  /**
   * Construct glide.
   *
   * @param  {String} selector
   * @param  {Object} options
   */
  constructor (selector, options = {}) {
    this._c = {}
    this._t = []
    this._e = new EventsBus()

    this.disabled = false
    this.selector = selector
    this.settings = mergeOptions(defaults, options)
    this.index = this.settings.startAt
  }

  /**
   * Initializes glide.
   *
   * @param {Object} extensions Collection of extensions to initialize.
   * @return {Glide}
   */
  mount (extensions = {}) {
    this._e.emit('mount.before')

    if (isObject(extensions)) {
      this._c = mount(this, extensions, this._e)
    } else {
      warn('You need to provide a object on `mount()`')
    }

    this._e.emit('mount.after')

    return this
  }
}

Notice how an instance of a eventBus is passed to each component (which can be a Arrow Component, Slider Component, Dots Component) of the slider plugin. This instance of eventBus than is used to communicate between all the components. I have a faint idea of how the pub/sub pattern works in JS. but What exactly is this pattern and what are the advantages of using it ?

Aucun commentaire:

Enregistrer un commentaire